在响应功能中,我需要使用Subscriptions再次调用相同的服务。
例如:
this.service.getData().subscribe(
result => {
if (result.length == 0) {
this.service.getData().subscribe(...);
}
}
);
当我单击按钮时,我需要再次订阅:
onClick() {
this.service.getData().subscribe(...);
}
我认为,这不是一个好方法。我将订阅3次。
如何正确解决此问题?
非常感谢您。
答案 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)