how to pass RouteData via Router.navigate in angular2

半世苍凉 提交于 2019-12-18 15:50:14

问题


Is there an api in agnular2 that allows passing json objects instead of string values . E.g. In Router.navigate() I can pass route parameters

Router.navigate('routename',[{key:stringvalue}])

and can retrieve it using RouteParams.get(key) : string. But this returns just string values. I need to pass the json object.

Appreciate any pointers


回答1:


I think that it's not something possible out of the box since routing relies on URLs and both path variables and query parameters are strings. Both RouterParams and RouterData only supports string attributes.

To simulate this, I don't see other solutions than encoding your JSON objects using JSON.stringify and parsing them on the other side.

Here is a plunkr describing this: https://plnkr.co/edit/jbl7v5fHQEmf4F8tpXDO?p=preview.

Hope it helps you, Thierry




回答2:


Another Solution that works is using the params Property of RouterParams. This may not be the preferred way, but it works (as of Beta8).

if you navigate with Router.navigate(['/myRoute',{someProperty:"SomeValue"}] you can access the param with:

constructor(routeParams: RouteParams){
  let myPassedData: any = routeParams.params;
  console.log(myPassedData.someProperty); #Prints "SomeValue"
}


来源:https://stackoverflow.com/questions/35034840/how-to-pass-routedata-via-router-navigate-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!