简体   繁体   English

如何在 angular2 中通过 Router.navigate 传递 RouteData

[英]how to pass RouteData via Router.navigate in angular2

Is there an api in agnular2 that allows passing json objects instead of string values . agnular2 中是否有允许传递 json 对象而不是字符串值的 api。 Eg In Router.navigate() I can pass route parameters例如在Router.navigate()我可以传递路由参数

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

and can retrieve it using RouteParams.get(key) : string .并且可以使用RouteParams.get(key) : string检索它。 But this returns just string values.但这仅返回字符串值。 I need to pass the json object.我需要传递json对象。

Appreciate any pointers感谢任何指针

Another Solution that works is using the params Property of RouterParams.另一个有效的解决方案是使用 RouterParams 的params属性。 This may not be the preferred way, but it works (as of Beta8).这可能不是首选方式,但它有效(从 Beta8 开始)。

if you navigate with Router.navigate(['/myRoute',{someProperty:"SomeValue"}] you can access the param with:如果您使用Router.navigate(['/myRoute',{someProperty:"SomeValue"}]导航,您可以使用以下方式访问参数:

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

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.我认为这不是开箱即用的,因为路由依赖于 URL,并且路径变量和查询参数都是字符串。 Both RouterParams and RouterData only supports string attributes. RouterParamsRouterData都只支持字符串属性。

To simulate this, I don't see other solutions than encoding your JSON objects using JSON.stringify and parsing them on the other side.为了模拟这一点,除了使用JSON.stringify对 JSON 对象进行JSON.stringify并在另一端解析它们之外,我没有看到其他解决方案。

Here is a plunkr describing this: https://plnkr.co/edit/jbl7v5fHQEmf4F8tpXDO?p=preview .这是一个 plunkr 描述这个: https://plnkr.co/edit/jbl7v5fHQEmf4F8tpXDO?p=preview

Hope it helps you, Thierry希望对你有帮助,蒂埃里

For Angualr 7,8+:对于 Angualr 7,8+:

sending end:发送端:

this.router.navigate(['/targeturl/' , JSON.stringify(inputParameter)]);

receiveing end:接收端:

import {  ActivatedRoute,  Router} ....

 sub;
  ngOnInit() {

this.sub = this.activatedroute.paramMap.subscribe(params => {
  console.log(params);
  debugger;
  }); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM