Warm tip: This article is reproduced from serverfault.com, please click

angular-订阅“可观察”:手动点火有可能吗?

(angular - Subcribed Oberservable: fire manually possible?)

发布于 2020-12-01 11:51:51

我有一个Oberservable来获取数据。

我使用Subscription在组件中的某个间隔中对其进行调用。

ngOnInit(){

this.subscr = interval (10000).pipe (
  startWith (0),
  mergeMap (obs => this.myservice.getData ().pipe (catchError (error =>
  {
    // error
  })))).subscribe (resp =>
  {
    // data
  });
}

ngOnDestroy ()
{
  this.subscr.unsubscribe ();
}

我喜欢通过操作(例如按钮)刷新数据。

refreshNow ()
{
  this.myservice.getData ().pipe (catchError (error =>
  {
    // error
  })))).subscribe (resp =>
  {
    // data
  });
}

但是我不喜欢在代码中多次使用getData。有什么方法可以手动触发this.subscr吗?

Questioner
chris01
Viewed
0
distante 2020-12-01 20:21:38

你可以使用Subject并将二者与merge()结合使用,例如:

private readonly triggerRefresh$$ = new Subject<void>();

// ....

this.subscr = merge(interval(10000), this.triggerRefresh$$)
    .pipe (
        switchMapTo(this.myservice.getData ()
            .pipe(catchError (error => {}))
        )
    ).subscribe (resp => {
        // data
      });


refreshNow () {
   this.triggerRefresh$$.next();
}