简体   繁体   中英

NgRX store.select returns store object instead of observable object

I have written a short example of Ngrx. I had no idea why this short code could not run properly.

constructor(private store: Store<CounterState>){
this.counter = store.select('counter');
console.log(this.counter);
}

This piece of code prints a Store object to the console instead of an observable. It is weird. The full version of the app please follow the link below. https://stackblitz.com/edit/angular-dq7ssf

Well, if you have a look at the Ngrx Store Source , Store is an Observable !

export class Store<T> extends Observable<T> implements Observer<Action> {
    ...
}

In the example you posted you're defining the rootstate with:

StoreModule.forRoot({  counterReducer })

Meaning that counterReducer is the key to access your counter state, to solve this you can select the counter as follows

this.counter = store.select('counterReducer', 'counter');

Or you could give your reducer a key:

StoreModule.forRoot({  counter: counterReducer });
this.counter = store.select('counter', 'counter');

In the post, when your writing store.select('counter') , it will return an observable and you assigned that to a property "counter".Now, the "counter" property also became an observable.To retrieve values from an observable, you need subscribe it.The below code will solve your problem.

//Rxjs 5 way

this.counter.subscribe(
(data:any) => {

console.log(data) //your data shows here
});

//Rxjs 6 way, with pipe operator

this.counter.pipe().subscribe(
(data:any) => {

console.log(data) //your data shows here
});

I hope, my answer will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM