How can I console.log the value of the observable?

I am using angular 2 and RxJS, and I am wondering how I can do the following:

In my component, I defined the following:

count: Observable<number>;

In my component constructor, I do the following:

 constructor( private store: Store<any> ) { this.count = this.store.select<any>(state => state.count); } 

How to view the current value for the account? Right now, if I console.log(this.count) , I get a large object to register. If I want to view only this.count, how can I do this?

+8
angular typescript rxjs
source share
1 answer

With a regular observable, you only get the value when it changes, so if you want console.log to output the value you will need to use console.log in the subscription:

 constructor( private store: Store<any> ) { this.count = this.store.select<any>(state => state.count); this.count.subscribe(res => console.log(res)); } 

However, if you want to get the current value at any time, then what you need is a BehaviorSubject (which combines Observable and Observer in functions ... imports it from the rxjs library, just like you, Observable).

 private count:BehaviorSubject<number> = new BehaviorSubject<number>(0); constructor( private store: Store<any> ) { let self = this; self.store.select<any>(state => self.count.next(state.count)); } 

Then, anytime you want to get the current counter value, you call this.count.getValue() to change the value you would this.count.next(<the value you want to pass in>) . This should get what you are looking for.

+9
source share

All Articles