2017-02-21 81 views
1

我正在通過發送用戶的用戶名和密碼來調用Web服務。如果給出錯誤的用戶名和密碼,我會收到401 UNAUTHORIZED錯誤。當想要在屏幕上輸出錯誤消息時,我希望能夠捕獲401發生的情況。Angular 2 - 在調用Web服務時如何捕獲401錯誤

這裏是調用服務的代碼:

return this.client.get<User>(this.BASEURL + 'api/id', new User(), null, encodedString) 
     .map(result => { 
      // If authorized, store the relevant information 
      if (result) { 
       result = new User().deserialize(result); 
      } 
      this.user.next(result); 
      return result; 
     }, this) 
     .catch(this.handleError); 

我試圖用一個嘗試捕捉周圍的整個事情,但它沒有做任何事情(我猜是因爲異步的)。我也試過console.log(result);如果(結果)後,但由於401錯誤,我永遠不會到達.map。我不知道如何處理這個問題。謝謝!

+0

'this.handleError'必須處理它。 – mxii

回答

2

您必須定義handleError方法。看看例子here