使用之前,请等待商店更新数据。 Rxjs /角度

时间:2018-10-01 08:25:14

标签: angular typescript rxjs

你好,我在rxjs中使用了angular,我需要找出一种方法,在分派一个动作来对该数据执行某些操作之后,等待商店更新其数据。到目前为止,这是我的component.ts

中相关代码的样子
  ngOnInit() {
  //subscribe to the store, get data from it
   this.store.pipe(select(selectors.getDataSelector)).pipe(takeUntil(this.destroy$)).subscribe(x => {
      this.data$ = x;
    });
  }

  updateData() {
    this.store.dispatch(new actions.getDataAction());
    // this action hits the http request, and stores the data in the store which is fetched with getDataSelector

    // now i need to do some condition that says `if the data in the store has completed updating after the action then do something
    if() {
      // do something with this.data$
    }
  }

1 个答案:

答案 0 :(得分:1)

如前所述,我不会在updateData函数中做出反应,而是在tap运算符中做出这样的反应:

  ngOnInit() {

   // Don't pipe multiple times as you did before
   this.store.pipe(
     select(selectors.getDataSelector),
     takeUntil(this.destroy$),
     tap((data) => this.foo())
   )
   .subscribe((data) => {
     this.data$ = data;
   });
  }

  updateData() {
    this.store.dispatch(new actions.getDataAction());
  }

  foo() {
    // do side-effects
  }