2017-02-23 107 views
1

我提供器提供了一個API,用於一個http.get要求:離子2:停止HTTP請求

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); 
        } 
       ); 
    }) 
} 

page.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中寫一個函數來停止這個循環。 我該如何殺死未決的獲取請求?

一個解決方案,不工作是 我試圖指針保持在觀察的對象在我page.ts:通過調用this.join_channel.unsubscribe()我想關閉請求

export class Page { 
    ... 
    join_channel: any; 
    join(){ 
    this.join_channel = this.myProvider.join().subscribe(
     (data)=>{ 
      ... 
       this.join(); 
      ... 

然後我,所以在我的情況下:

ionViewWillLeave() { 
    this.join_channel.unsubscribe(); 
    delete this; 
    } 

但即使通過取消訂閱,獲取請求仍然存在掛起;所以當我嘗試在我的頁面中再次輸入時,新的join()無法在第一步中收到http.get響應,因爲之前的請求仍在等待處理。從rxjs

回答

1

使用超時

this.http.get(API) 
    .timeout(2000) 
    .map(res => res.json()).subscribe((data) => { 
     return data; 
    }, 
     (err) => { 
     return err; 
     } 
    ); 

不要忘了導入import 'rxjs/add/operator/timeout';

+0

但超時自動殺死請求;我需要不同的東西:應該在'ionViewWillLeave()'關閉請求' – pittuzzo

+0

我認爲它正在工作,但實際上也取消訂閱()並不真正殺死http.get – pittuzzo