我怎样才能console.log一个可观察对象的值?



我正在使用angular 2和RxJS,我想知道我怎么能做到以下几点:

在我的组件中,我定义了以下内容:

count: Observable<number>;

在我的组件的构造函数中,我做了以下操作:

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

如何查看计数的当前值?现在,如果我用console.log(this.count),我得到一个大的对象。如果我只想看这个的值。伯爵,我该怎么做呢?

对于一个常规的可观察对象,你只在它改变的时候得到它的值,所以如果你想要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));
  }

然而,如果你想在任何时候都能获得当前值,你需要的是一个行为学主题(它结合了一个可观察对象和一个观察者的功能…从rxjs库中导入,就像你做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));
  }

然后任何时候你想要获得当前的计数值,你会调用this.count.getValue()来改变你会调用this.count.next(<the value you want to pass in>)的值。

对于最近版本的RxJS(从6.0开始的AFAIR),正确的方法是使用.pipe()。为了回答你的问题,你需要tap运算符。

constructor(
    private store: Store<any>
  ) {
    this.count = this.store.select<any>(state => state.count).pipe(
        tap(countValue => console.log('Count: ', countValue))
    );
  }

相关内容

最新更新