使用RxJS在另一个订阅中进行相同的订阅

时间:2019-11-28 13:59:17

标签: angular rxjs

在响应功能中,我需要使用Subscriptions再次调用相同的服务。

例如:

this.service.getData().subscribe(
  result => {
    if (result.length == 0) {
      this.service.getData().subscribe(...);
    }
  }
);

当我单击按钮时,我需要再次订阅:

onClick() {
  this.service.getData().subscribe(...);
}

我认为,这不是一个好方法。我将订阅3次。

如何正确解决此问题?

非常感谢您。

2 个答案:

答案 0 :(得分:0)

您可以使用switchMap()

this.service.getData().pipe(
    switchMap(data => {
        // work with 'data'
        if (data.length === 0) {
            return this.service.getData();
        }
        return of(undefined);
    }),
).subscribe(result => {
    // work with 'result'
});

在您的情况下,如果第一个请求返回错误,如果您想再次发送相同的请求,则可以使用retry()

有关retry()的文档:https://rxjs-dev.firebaseapp.com/api/operators/retry

答案 1 :(得分:0)

我建议您将获取数据逻辑放在一个方法中,您可以重用该方法。我使用switchMap来链接可观察对象,而使用of来创建一个填充有数据的可观察对象。

class MyService {
  ...

  getData() {
    return this.service.getData().pipe(
      switchMap(data => {
        return data.length > 0 ? of(data) : this.getData();
      })
    );
  }

  onClick() {
    this.getData().subscribe(data => {
      console.log(data);
    })
  }
}