2017-05-29 45 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