Exploring the method to effectively subscribe to state changes in Angular 7 reducers

I have implemented Redux with Angular 7, and I am successfully adding values to the state. However, I am unsure of how to subscribe to changes in the state.

Below is the code snippet that I have attempted:

Selectors

export const selectProfessionalLearningTeacherFeature =
  createFeatureSelector<any>('professionalLearningTeacher');

export const selectProfessionalLearningTeachers =
  createSelector(selectProfessionalLearningTeacherFeature, (state) => state.professionalLearningTeacher);

Sports Component

@Component({
  selector: 'app-sports-practice',
  templateUrl: './sports-practice.component.html',
  styleUrls: ['./sports-practice.component.scss']
})
export class SportsPracticeComponent implements OnInit {


  constructor(private fb: FormBuilder, private professionalLearningService: ProfessionalLearningService,private _store: Store<any>) {
    this._store.select(selectProfessionalLearningTeachers)
  .pipe(takeUntil(this._ngOnDestroy)).subscribe(item => {
    console.log(item);
  });
   }

  ngOnInit() {  }

}

Here is my reducer component

const meta: any = '';
const ProfessionalLearningTeachers: any = '';
const INITIAL_STATE: any = {
  meta,
  ProfessionalLearningTeachers
}
export function ProfessionalLearningTeacherReducer() {
  return function entityReducer(
    state: any = INITIAL_STATE,
    a: Action,
  ): any {
    const action = a as EntityAPIAction;
    if (!action.meta) {
      return state;
    }
    let itemIndex = -1;

    switch (action.type) {
      case ProfessionalLearningTeacherApiActions.PROFESSIONAL_LEARNING_TEACHER_SAVE_SUCCEEDED:
        return storeProfessionalLearning(state, action);
    }
    return state;
  };
}

function storeProfessionalLearning(state, action): any {
  return Object.assign({}, state, {
    meta: action.meta,
    ProfessionalLearningTeachers: action.payload,
  });
}

The state diagram

https://i.sstatic.net/0ChJk.png

Console Output

https://i.sstatic.net/cchpT.png

https://i.sstatic.net/6hCOn.png

Reference

Listening to Redux State Changes in Angular (v5)

Angular Redux Select Pattern

Answer №1

To enhance your code, consider employing a selector.

professionalLearningTeacher.selectors.ts:

import { createFeatureSelector, createSelector } from '@ngrx/store';

export const selectProfessionalLearningTeacherFeature =
  createFeatureSelector<ProfessionalLearningTeacherState | any>('professionalLearningTeacher');
// Instead of 'professionalLearningTeacher', use a const for better practice

export const selectProfessionalLearningTeachers =
  createSelector(selectProfessionalLearningTeacherFeature, (state) => state.professionalLearningTeachers);

portsPracticeComponent.ts:

@Component({
  selector: 'app-sports-practice',
  templateUrl: './sports-practice.component.html',
  styleUrls: ['./sports-practice.component.scss']
})
export class SportsPracticeComponent implements OnInit {
  professionalLearningTeachers$: Observable<any>;

  constructor(
    private _store: Store<IAppState>
  ) {

  }

  ngOnInit() {
    this.professionalLearningTeachers =  this._store.select(selectProfessionalLearningTeachers)
    .pipe(takeUntil(this._ngOnDestroy));
  }
}

Note the following:

  • IAppState should match your state type; adjust as needed.
  • Avoid using any for specific types in your code for better practice.
  • Refactor state properties to start with lowercase letters, like 'professionalLearningTeachers'.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on assigning a selected option value to the upload file

The user interface has a selection of documents for the user to choose from. I am trying to associate the fileType with the image that will be uploaded through the input tag. Although I can retrieve the value of the selected document from the drop down usi ...

Checking for queryParam changes in Angular before ngOnDestroy is invoked

I am looking to conditionally run some code in the ngOnDestroy function depending on changes in the current route. Specifically, when the route changes from /foo to /login?logout=true, and this change is initiated outside of the Foo component. In the ngO ...

There seems to be an incorrect number of arguments in the `getDownloadURL` function for Firebase Storage. It was expected to receive

I need assistance with retrieving the download URL of an image immediately after uploading it. Here is the code I am using: let image : string = 'promo_' + this.username + '_' + new Date() + '.png', storageRe ...

How can I access a DOM element in an AngularJS 2 TypeScript file?

As a newcomer to AngularJS, I am attempting to add a spinner as a background to all images on my website. Since there are multiple images, using a single variable like isLoaded in the TypeScript file is not feasible. Here is how I am implementing it in th ...

Disconnect issue in NodeJS socket.IO occurs when attempting to send a large JSON object

In the process of developing a layered card game similar to Hearthstone, I am utilizing a Node.js back-end and an Angular front-end. I attempted to establish a connection between the two using Socket.IO. However, I encountered issues when sending a JSON o ...

Using ngb-carousel to display embedded YouTube iframe videos

Can anyone help me figure out how to embed an Iframe into a ngb-carousel? The carousel is displaying correctly, but the iframe tab is not showing up as expected. <ngb-carousel *ngIf="project.images"> <ng-template class="item" n ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

What is the best way to prevent executing a method in [queryParams] in Angular 7?

I'm currently working on incorporating the option for users to open a link in a new tab. I'm trying to avoid using the (click) method, so I've come up with the following logic to achieve this: <a [routerLink]="['/search/' + sea ...

Troubleshooting `TypeError: document.createRange is not a function` error when testing material ui popper using react-testing-library

I am currently working with a material-ui TextField that triggers the opening of a Popper when focused. My challenge now is to test this particular interaction using react-testing-library. Component: import ClickAwayListener from '@material-ui/core/ ...

Translate the TypeScript interface to its corresponding interface

Imagine having a TypeScript interface like this: interface IOriginal { aaa: string; bbb: boolean; } Now, let's say you want to create a similar interface with the same keys but different values (in this scenario, the values are generated usi ...

Are there any solutions available for sending a POST request before closing a tab?

Currently, I am in need of a solution that allows me to unlock a deal when the tab is closed. The challenge lies in the fact that the lock status is stored in my database, and I must make a POST request upon tab closure to change the status of the deal to ...

Angular's keyevent is acting similarly to a tab when the input field is disabled

I've encountered some strange behavior with my input field. Every time a user presses the enter or space key, I want to execute some actions. Once the key is pressed, I need to disable the field until the actions are complete. Pressing the *enter ke ...

Issue with @Arg Type Error arising while utilizing a GraphQL class imported from a local Package in TypeGraphQL

I have developed a local package containing various objects. The main purpose of this package is to be installed via npm in other programs so that they can utilize a common library of objects. One of the objects I created is a simple class for setting up a ...

In Vue, you can dynamically load a JavaScript file containing a JavaScript object during runtime

I'm in the process of developing a no-code application with Vue. I have come across an issue where I cannot add functions to a JSON file that I want to import at runtime. As a workaround, I decided to use a JavaScript or TypeScript file to store the J ...

Utilizing Angular 7 to reference images via a content delivery network (CD

Is there a way to update the image sources from <Img src='./assets/abc.svg'> to <Img src='cdn.example.com/abc.svg'>? I am looking to change all of the image paths. I have explored options like --deployUrl and baseHref, but ...

Can Angular be integrated into an established .NET MVVM Project?

My current project lacks a traditional front-end setup, instead using razor views on top of an application. These views interact with the view model to access data. I am interested in incorporating Angular into my existing project to modularize some of the ...

Unable to retrieve query parameters from the ActivatedRoute class

I currently have a route set up in the routing module like this: { path: 'warning/:type', component: WarningPageComponent } When the application needs to navigate to the warning page, it makes this call: const navigationExtras: NavigationExtras ...

Identifying browsers in Angular - a comprehensive guide

Does Angular (TypeScript) have the capability to identify whether the browser being used is either IE or Edge? If so, what method can be employed to accomplish this task? ...

Properly showcase a list of data in a mat-table with dynamically grouped columns

I have encountered an issue that is proving difficult for me to solve. Upon making a request to my API, I receive a dataset structured like this: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, ty ...

Angular 11 is giving an error message stating that the 'async' pipe cannot be located

Struggling to fetch data using Angular 11 as an observable? Issues arise when using async or JSON pipe in a lazy loaded component/module, resulting in errors displayed in the console. The module: import { NgModule } from '@angular/core'; import ...