2016-11-18 128 views
2

我有以下問題:我有一個角2應用程序,它發出這樣的GET請求:如何在Angular2中處理獲取請求到離線源?

getStatus(cb:(boolean, error) => void){ 
    this.http.get(this.uri+'/forms/status') 
    .subscribe(
     (res: Response) =>{ 
      console.dir(res); 
      this.response = res; 
      if(res.status === 200)cb(true, null); 
      else cb(false, "No connection established"); 
     } 
    ) 
} 

那麼這種方法應該檢查,如果我的服務是在線與否,應該將消息發送給用戶,如果它離線。我的問題是,我總是會得到

無法加載資源:net :: ERR_CONNECTION_RESET 當我調用該方法。 我的問題是我如何處理它,該方法只是返回布爾值爲false,當我的服務處於脫機狀態。

此致敬禮。

切換到

getStatus(cb:(boolean, error) => void){ 
this.http.get(this.uri+'/forms/status') 
.map(val => true) 
.catch(err => Observable.of([false]) 
.subscribe(
    (res: boolean) => cb(res, res ? null : "No connection established");) 
} 

返回錯誤信息:

ERROR in [default] C:\Development\Code\formcreator-ui\app\src\service\form.servi 
ce.ts:66:8 
Argument of type '(res: boolean) => void' is not assignable to parameter of type 
'NextObserver<boolean[]> | ErrorObserver<boolean[]> | CompletionObserver<boolea 
n[]> | ((value: boo...'. 
    Type '(res: boolean) => void' is not assignable to type '(value: boolean[]) => 
void'. 
    Types of parameters 'res' and 'value' are incompatible. 
     Type 'boolean[]' is not assignable to type 'boolean'. 

回答

0

如果你指的是在瀏覽器控制檯來取消錯誤信息,那麼你的運氣了。這個錯誤是由瀏覽器創建的,沒有辦法避免它。

否則這應該做你想做的。

getStatus(cb:(boolean, error) => void){ 
    this.http.get(this.uri+'/forms/status') 
    .map(val => true) 
    .catch(err => Observable.of([false]) 
    .subscribe(
     (res: Response) => cb(res, res ? null : "No connection established"); 
    ) 
} 

但不是cb我會不喜歡它

getStatus(){ 
    return this.http.get(this.uri+'/forms/status') 
    .map(val => true); 
    .catch(err => Observable.of([false]) 
} 

那麼就可以使用像

this.getStatus().subscribe(avail => avail ? doSomething() : console.log("No connection")); 

觀測量,以避免回調地獄,因此使用這個功能是首選,而不是通過回調周圍。

+0

當我嘗試這個時,它在map(true)時失敗,「布爾類型的Argumebnt不能分配給類型的參數(value:boolean [],index:number)」 – LordHW4

+0

您可以嘗試'Observable.of假)'?我自己不使用TS,也不完全確定所有細節。 –

+0

也不起作用。它適用於mapTo(true),但是我無法訂閱它。 – LordHW4