简体   繁体   English

angular2 RouteParams、序列化和复杂对象或数组

[英]angular2 RouteParams, serialization, and complex objects or arrays

I am trying to pass an object as a RouteParam我正在尝试将对象作为 RouteParam 传递

let params = { account: 'revenue', page: 3, conditions: [{foo: 'john'}, {foo: 'kelly'}] // <-- Complex object } this._router.navigate(['Journal', params])

but I am getting a URL like但我得到一个像

http://localhost:3000/journal/revenue/3?conditions=[object%20Object],[object%20Object]

IIRC, angular1 supported this type of serialization back and forth using JQuery's $.param (I might be wrong) IIRC,angular1 支持使用 JQuery 的 $.param 来回这种类型的序列化(我可能错了)

Is there a way to achieve similar in angular2?有没有办法在 angular2 中实现类似的目标?

Because such parameters are passed within the URL, you could convert them as string using for example JSON.stringify and convert them to object from route params using JSON.parse when you want to access them.由于此类参数在 URL 内传递,因此您可以使用例如JSON.stringify将它们转换为字符串,并在您想要访问它们时使用JSON.parse将它们从路由参数转换为对象。

let params = { 
  account: 'revenue', 
  page: 3, 
  conditions: JSON.stringify("[{foo: 'john'}, {foo: 'kelly'}]") 
};
this._router.navigate(['Journal', params]);

and

constructor(params:RouteParams) {
  var conditions = JSON.parse(params.get('conditions'));
}

The other approach is to use a shared service.另一种方法是使用共享服务。 You set the object into a property of this service before calling the route and get it from the component corresponding to the route after it was activated.您在调用路由之前将对象设置为该服务的一个属性,并在路由激活后从与该路由对应的组件中获取它。 You can notice that a shared service needs to be defined when bootstrapping your application to be able to share a single instance for the whole application:您会注意到在引导应用程序时需要定义共享服务,以便能够为整个应用程序共享单个实例:

bootstrap(AppComponent, [ SharedService ]);

See this question for more details:有关更多详细信息,请参阅此问题:

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

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