Reputation: 33
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
Upvotes: 3
Views: 3308
Reputation: 73
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.
Upvotes: 1
Reputation: 15525
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');
Upvotes: 1
Reputation: 441
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> {
...
}
Upvotes: 0