use*_*934 18 rxjs typescript angular
我正在使用角度2和RxJS,我想知道我如何能够做到以下几点:
在我的组件中,我定义了以下内容:
count: Observable<number>;
在我的组件的构造函数中,我正在执行以下操作:
constructor(
private store: Store<any>
) {
this.count = this.store.select<any>(state => state.count);
}
Run Code Online (Sandbox Code Playgroud)
如何查看计数的当前值?现在如果我console.log(this.count)
得到一个大对象来记录.如果我只想查看this.count的值,我该怎么做?
小智 20
使用常规observable只会在更改时获取值,因此如果您想要console.log输出值,则需要在订阅中使用console.log:
constructor(
private store: Store<any>
) {
this.count = this.store.select<any>(state => state.count);
this.count.subscribe(res => console.log(res));
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您希望能够随时获得当前值,那么您将需要的是一个BehaviorSubject(它在函数中结合了一个Observable和一个Observer ......从像Observable一样从rxjs库中导入它).
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));
}
Run Code Online (Sandbox Code Playgroud)
然后,只要你想获得计数的当前值,你就可以调用它this.count.getValue()
来改变你要调用的值this.count.next(<the value you want to pass in>)
.这应该可以满足您的需求.
对于 RxJS 的最新版本(AFAIR 从 6.0 开始),正确的方法是使用.pipe()
. 要回答您的问题,您需要tap
操作员。
constructor(
private store: Store<any>
) {
this.count = this.store.select<any>(state => state.count).pipe(
tap(countValue => console.log('Count: ', countValue))
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18250 次 |
最近记录: |