我在这里向社区提出的第一个问题!我正在开发一个应用程序,它通过以下方式与API通信
step1: 创建请求选项,添加请求有效负载 - >向API发布请求
API使用请求ID进行响应
Step2: 更新请求选项,将请求ID作为有效负载发送 - >将请求发送到API
最终答复:response.json
现在,最终响应可能需要一些时间,具体取决于所请求的数据 . 这平均可以在4到20秒之间 .
我如何使用observable链接这些请求,我尝试使用switchmap并失败(如下所示),但不知道如何添加间隔?是否每4秒轮询一次并取消订阅响应是否可行?在上述背景下如何做到这一点?
Edit1: 结束目标:我希望了解前进的最佳方式..在这种背景下链接可观察的帮助吗?即在初始响应之后有某种间隔并使用flatMap或使用带间隔的轮询来检查报告是否准备就绪 .
这是我到目前为止所拥有的
export class reportDataService {constructor(private _http:Http){}
headers: Headers;
requestoptions: RequestOptions;
payload: any;
currentMethod: string;
theCommonBits() {
//create the post request options
// headers, username, endpoint
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: newheaders,
body: JSON.stringify(this.payload)
})
return this.requestoptions;
}
// report data service
reportService(payload: any, method: string): Observable<any> {
this.payload = payload;
this.currentMethod = method;
this.theCommonBits();
// fetch data
return this._http.request(new Request(this.requestoptions))
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
in my component
fetchData() {
this._reportService.reportService(this.payload, this.Method)
.switchMap(reportid => {
return this._reportService.reportService(reportid, this.newMethod)
}).subscribe(
data => {
this.finalData = data;
console.info('observable', this.finalData)
},
error => {
//console.error("Error fetcing data!");
return Observable.throw(error);
}
);
}
1 回答
如何在服务中使用Promise而不是Observable,以及组件中的.then()方法 . 您可以链接尽可能多的.then(),以便在它们之间链接操作 .