这里,如果挂起的服务> 0,我想调用一个服务(Http api)来获取新的状态。为此,我编写了以下代码:
counter = 1;
getDetatils(){
this.myService.getDetails().subscribe(services => {
this.services = services;
if(this.services.pending.length > 0 && counter <= 10){
this.getDetails(); // if list of pending item is > 0, do query again.
counter ++;
}
})
在上面的代码中,继续运行函数getDetails,除非挂起的服务列表为0(最多10次)。
但不知何故,我对上面的代码结构并不满意。第一件事,我不想每秒都轮询。可能是在5点之后轮询。不知何故,我讨厌使用超时。
我尝试在这里使用Observable,但作为angular2的新手,不确定它的确切用法。
所以我的问题是,我可以在这里使用Observable,它同时考虑间隔和最大尝试吗?如果是,那么是如何实现的?以及如果不满足某些条件,我将如何取消此操作。
发布于 2017-05-15 13:17:37
是否可以将待处理请求的列表转换为可观察的列表?
class MyPendingService {
private pending: Subject<any> = new Subject();
get pendingRequests(): Observable<any> {
return this.pending.asObservable();
}
queueRequest(x: any) {
this.pending.next(x);
}
}
// Somewhere else in your codebase you consume your observable
// ...
pendingService.pendingRequests.subscribe((next) => {
// Replace this with your logic
console.log("pending", next);
});
// In another place, you produce pending pending requests
// ...
pendingService.queueRequest("1");
pendingService.queueRequest("2");
查看这个柱塞器以获得最小的示例实现:https://embed.plnkr.co/9fLBH3YA7BlQw6ndZCFp/
https://stackoverflow.com/questions/43962924
复制