3
votes

I am new to ngrx and what to ask, with ngrx, is there any way to subscribe the change of one field in state.

Suppose I have state as

export interface AppState {
    fieldA: boolean;
    fieldB: string;
};

Now in a component if I have

this.appState$ = store.select('appState');
this.appState$.subscribe((state) => {
    this.fieldA= state.fieldA;
});

Then even fieldB is changed, the subscription will be triggered as well. Although I can filter it by checking whether or not fieldA is changed or not, is there build-in function in ngrx so that I can only subscribe the change of fieldA.

I tried

store.select(s => s.fieldA).subscribe((fieldA) => {
    this.fieldA= fieldA;
});

But even fieldA is changed, seems like this subscription is not triggered.

Thanks.

1
so you want to subscribe only when filedA changes? no when fieldB? is that correct?Sergio Alen
yes, this is correct. But I want to have fieldA and fieldB in state so that in another component, I can subscribe the change of fieldB only.Ben

1 Answers

5
votes

You should

store.select('fieldA').subscribe((fieldA) => {
    this.fieldA= fieldA;
});

Or, if you want to go deeper, you should pay attention to selectors.