经过大量研究,我可以从 RxJs' 6 和 Angular 6 中提出以下更新的方法。
搜索 API 在每 5 秒间隔后调用一次,并且在计数 > 5 后取消订阅:
let inter=interval(5000)
let model : ModelComponent;
model=new ModelComponent();
model.emailAddress="mdshahabaz.khan@gmail.com";
let count=1;
this.subscriber=inter.pipe(
startWith(0),
switchMap(()=>this.asyncService.makeRequest('search',model))
).subscribe(response => {
console.log("polling")
console.log(response.list)
count+=1;
if(count > 5){
this.subscriber.unsubscribe();
}
});
API 请求:
makeRequest(method, body) : Observable<any> {
const url = this.baseurl + "/" + method;
const headers = new Headers();
this.token="Bearer"+" "+localStorage.getItem('token');
headers.append('Authorization', this.token);
headers.append('Content-Type','application/json');
const options = new RequestOptions({headers: headers});
return this.http.post(url, body, options).pipe(
map((response : Response) => {
var json = response.json();
return json;
})
);
}
不要忘记取消订阅以避免内存泄漏。
ngOnDestroy(): void {
if(this.subscriber){
this.subscriber.unsubscribe();
}
}