Ionic 2:停止http请求
My provider为Ionic 2:停止http请求,http,ionic2,rxjs,Http,Ionic2,Rxjs,My provider为http提供API。获取请求: join(){ let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('x-access-token',this.getToken()); return Observable.create(observer =>{ this.http.get('/lo
http提供API。获取请求:
join(){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('x-access-token',this.getToken());
return Observable.create(observer =>{
this.http.get('/localhost/chat/'+this.room,{headers : headers})
.map(res => res.json())
.subscribe(
data=>{
observer.next(data);
},
(err) =>{
observer.error(err);
}
);
})
}
Mypage.ts
只需循环使用此API即可:
join(){
this.myProvider.join().subscribe(
(data)=>{
if(data.success){
... /* doing smt */ ....
this.join();
}else{
this.message=data.message;
//TBD sleep....
//this.join();
}
},
(err) => {
this.message="Connectivity with server Lost...";
});
}
我的问题是:我想在page.ts
中写一个函数来停止这个循环。
如何终止挂起的get请求
一个不起作用的解决方案是
我试图在我的页面中保留一个指向可观察对象的指针。ts
:
export class Page {
...
join_channel: any;
join(){
this.join_channel = this.myProvider.join().subscribe(
(data)=>{
...
this.join();
...
然后我通过调用this.join\u channel.unsubscribe()
来关闭请求,因此在我的情况下:
ionViewWillLeave() {
this.join_channel.unsubscribe();
delete this;
}
但即使取消订阅,get请求仍在等待处理;因此,当我再次尝试在页面中输入时,新的join()
无法在第一步收到http.get响应,因为之前的请求仍在等待中,所以答案将用于该请求。使用rxjs的超时
this.http.get(API)
.timeout(2000)
.map(res => res.json()).subscribe((data) => {
return data;
},
(err) => {
return err;
}
);
不要忘记导入导入'rxjs/add/operator/timeout'代码>如果您使用的是angular 6
,则必须使用
管道(超时(2000))
但是超时会自动终止请求;我需要一些不同的东西:应该在ionViewWillLeave()
上关闭请求,我以为它在工作,但实际上取消订阅()并不会真正杀死http。Get你做到了吗?找到的解决方案是将观察者保留在我的页面中。ts:export类页面{…join\u通道:any;join(){this.join_channel=this.myProvider.join().subscribe((数据)=>{…this.join();…然后我就可以通过这个来终止get请求。join_channel.unsubscribe()。在我的例子中:ionViewWillLeave(){this.join_channel.unsubscribe();删除这个;}
this.http.get(API)
.pipe(timeout(2000))
.map(res => res.json()).subscribe((data) => {
return data;
},
(err) => {
return err;
}
);