2017-05-29 90 views
0

我不知道如何在請求(組件)之間傳輸數據。我需要從ErrorComponent的任何組件傳輸錯誤並顯示錯誤消息和http狀態碼。 我試試這個:Angular2 - 從url獲取參數skipLocationChange

this.router.navigate(['/error', { error: error }], { skipLocationChange: true }); 

但我不知道如何從URL錯誤參數(在瀏覽器的錯誤論點心不是)。我知道skipLocationChange = false時,我看到url中的錯誤,但我不想看到它。 如何將錯誤處理程序中的錯誤傳輸到errorcomponent以顯示錯誤消息?我如何知道我有哪個http錯誤代碼? 由於

+0

您可以使用服務傳輸兩個組件之間的錯誤消息。請參閱此鏈接https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service –

+0

謝謝,這很好。但我有下一個問題。我的服務有屬性錯誤,哪種類型是錯誤。現在我需要顯示http狀態碼。在http.get()我會得到它的代碼404.我創建類屬性代碼HttpError,但是當我在服務屬性錯誤,我仍然錯誤,我不知道狀態代碼。 – bluray

+0

你爲什麼不把錯誤代碼與路由器中的數據部分一起發送.navigate函數,以便以後不需要解析它。我:e把它作爲字符串發送 –

回答

0

從app.routing文件的標準方法

@RouteConfig([ 
    {path: '/error', component: ErrorComponent, 
    as: 'Error', data: {error: '404' // or your component variable the info you get from service}}]) 

export class ErrorComponent{ 
    error: string; 
    constructor(params: RouteParams, data: RouteData) { 
     this.productID = params.get('error'); 

     console.log('Error is ', data.get('error')); 
    } 
} 

在這樣

this.router.navigate(['/a4',{message:"Not Authorised"}]); 

組件使用,並在誤差分量訪問像

this.message = this.route.snapshot.params['message']; //you can even subscribe to the value here to listen for changes 
+0

謝謝,但我有小問題。我不明白你的例子的任何部分。在路由配置你有數據{錯誤:404},但從服務器我得到不同的狀態代碼,404,400,401 ...如何添加我從服務器獲得的代碼?在第二個例子中,你有消息,我想發送錯誤消息,狀態碼,也許調用堆棧(用於調試),但我不會顯示在URL中的這些數據。對不起,我是angular2的新手。感謝:) – bluray

+0

這是另一種方式,當你從你的app.routing發送靜態數據。如果你想發送通過this.router.navigate發送的任何數據(['/ a4',{message:「Not Authorized」}]);更改消息值而不是字符串使用變量 –

+0

是的,我知道我寫錯誤處理程序是這樣的(['/ a4',{message:error.message,statusCode:error.statusCode,error:error}]);但是我在url中看到的這個數據,這是好還是不好? – bluray