在angular项目中使用rxjs的Http轮询和条件逻辑
我正处于Angular 4项目的早期阶段,试图为我的http服务创建一个客户端。这些服务可以返回以下两种情况之一:在angular项目中使用rxjs的Http轮询和条件逻辑,angular,rxjs,observable,Angular,Rxjs,Observable,我正处于Angular 4项目的早期阶段,试图为我的http服务创建一个客户端。这些服务可以返回以下两种情况之一: http状态为200的服务的实际所需json响应,或 表示作业令牌的guid,我可以用它轮询长期运行作业的状态,http状态为202 当服务返回200状态时,我只想直接返回它的json内容,这很简单 当结果状态为a 202时,我希望使用该令牌轮询一个单独的url,并接收一个带有状态信息的json对象。当该状态信息指示完成时,我想请求返回输出的最终url 我不确定如何处理请求中需要的
repeatWhen
来监视轮询请求的结果,但我很难弄清楚如何使用它
http.request('/some/longrunning/job')
.flatMap((resp: Response) => {
if (resp.status !== 202)
return Observable.of(resp);
var job_token = resp.json().token;
return http.get('/jobstatus/' + job_token)
// result from this endpoint is a json object that looks something
// like { status: 'running' } or { status: 'complete' }
.repeatWhen(function (polling_resp: Observable<Response>) {
// How do I use polling_resp here to look at my http response?
// Do I need to explicitly subscribe to it? And if so,
// how then do I inspect the response and return the
// appropriate value to indicate whether or not to
// resubscribe via the repeatWhen?
});
});
http.request('/some/longrunning/job')
.flatMap((响应)=>{
如果(响应状态!==202)
可观察的回报率(resp);
var job_token=resp.json().token;
返回http.get('/jobstatus/'+job_标记)
//这个端点的结果是一个json对象,看起来像
//例如{status:'running'}或{status:'complete'}
.repeatWhen(功能(轮询响应:可观察){
//如何在此处使用polling_resp查看http响应?
//我需要明确订阅吗?如果需要,
//那么,我如何检查响应并返回
//用于指示是否
//通过repeatWhen重新订阅?
});
});
有人能给我一些关于如何在
repeatWhen
中使用逻辑的提示吗?我还没有看到任何使用observable本身的内容来决定是否重新订阅的例子。我认为您正在寻找类似的内容:
http.request('/some/longrunning/job')
.flatMap((resp: Response) => {
if (resp.status !== 202)
return Observable.of(resp);
const token = resp.json().token;
return http.get(`/jobstatus/${token}`)
// You can use repeatWhen if you need more nuanced logic for
// how many times you want this to repeat, and how it should
// space out repeat attempts.
// This is just an example that guarantees at least 1 second between
// poll attempts so as to not overload the server
.repeatWhen(c => c.debounceTime(1000))
// Ignore values until you have completed
.skipWhile(resp => resp.json().status !== 'completed')
// At this point you can stop the polling
.take(1)
// You don't actually care about the value of the response
// just that it has "completed" this maps that response to the
// call to fetch the result status.
.flatMapTo(http.get(`/jobresult/${token}`))
});
基本上,您的第一个条件是正确的,第二部分您需要启动请求并不断重复它,skipWhile
部分将检查结果,并且在状态标记为完成之前不会传播它们,然后,您可以使用flatMapTo
将生成的消息直接转换为另一个API请求,以获得实际结果,然后进行传播