2017-05-04 82 views
0

我有我想如果響應是401,403,還是500像那麼回事可觀察到的服務:捕不捕誤差角2

post(url, data) { 
     let headers = new Headers(); 
     headers = this.createAuthorizationHeader(headers); 
     return this.http.post(url, data, { 
      headers: headers 
     }).catch(this.catchAuthError(this)); 
    } 

catchAuthError方法:

private catchAuthError (self: HttpUtil) { 
     // we have to pass HttpService's own instance here as `self` 
     return (res: Response) => { 

      if (res.status === 401 || res.status === 403 || res.status === 500) { 

       //TODO: route the user to the login page again and make a 500 ERROR page 
       // if not authenticated 
       console.log("ERROR: "+res); 

       this.relogin.showDialog(); 

      } 
      return Observable.throw('Not authenticated: '+res); 
     }; 
    } 

我不知道爲什麼該方法沒有被觸發,但網絡選項卡(chrome)自然會告訴我我得到了哪個錯誤。但是控制檯未顯示console.log("ERROR: "+res);

+0

AFAIK傳遞給'捕獲的錯誤處理程序(......)'會得到錯誤傳遞,而不是'Response'。你檢查過了嗎?你也不需要傳遞'this' /'self',如果你使用箭頭函數'this'將繼續在'catchAuthError'中工作(比如'})catch((e)=> this.catchAuthError(e) );' –

回答

1

您的輸入參數都有一個錯誤的類型

確保您導入

import 'rxjs/add/operator/catch'; 

修改代碼如下

post(url, data) : Observable<Response> { 
     let headers = new Headers(); 
     headers = this.createAuthorizationHeader(headers); 
     return this.http.post(url, data, { 
      headers: headers 
     }).map(res => res.json()) 
     .catch(this.catchAuthError); 
    } 



private catchAuthError(res: Response) { 
      if (res.status === 401 || res.status === 403 || res.status === 500) { 

      //TODO: route the user to the login page again and make a 500 ERROR page 
      // if not authenticated 
      console.log("ERROR: "+res); 

      this.relogin.showDialog(); 

     } 
     return Observable.throw('Not authenticated: '+res); 

    } 

LIVE DEMO

1

您的代碼應該更多這樣的:

post(url, data) { 
    let headers = new Headers(); 
    headers = this.createAuthorizationHeader(headers); 
    return this.http.post(url, data, { headers: headers }) 
      .catch((err)=> this.catchAuthError(err)); //** use arrow notation here 
} 

private catchAuthError (error) { 
    console.log(error); //**then depending on your error object fill the below lines 
    if (error.status === 401 || error.status === 403 || error.status === 500) { 

     console.log("ERROR: "+ (error.message || error)); 

     this.relogin.showDialog(); 
    } 

    return Observable.throw('Not authenticated: '+error); 
}