2017-05-09 35 views
0

我正在使用Http連接到服務器。Angular2是否可以使用http錯誤消息?

服務器通過給我403 forbidden error自動阻止未經授權的用戶。

雖然我不需要使用AuthGuard(coz服務器正在爲我做),但是我仍然希望在返回403禁止錯誤時顯示一些消息,而不是僅顯示空白頁面。

所以我的問題是..是否有可能在Angular2中使用這個禁止的403錯誤,這樣我可以在錯誤返回時顯示一些東西?

if (errorMessage == 403) { 
showModal() } 

也許這樣嗎?

+0

這是可能的,因爲你應該得到來自服務器的響應。您需要創建一個403錯誤的HTML頁面並將其顯示爲 –

+0

,並且可以告訴我該怎麼做?像爲403錯誤的HTML頁面創建另一個組件? – Lea

回答

1

的simples例子只是

@Inject export default class SomeService { 
    constructor(readonly http: Http) {} 

    getData() { 
    return this.http.get('api/path-to-something') 
     .catch(error => { 
     if (error.status === 403) { 
      // Just using alert for simplicity's sake. 
      alert('You don't have sufficient access to do that!'); 
     } 
     throw error; 
     }) 
     .map(response => response.json()); 
    } 
} 
相關問題