2017-06-21 260 views
0

我已经使用Angular2中的辅助路由配置了路由器配置。所以我需要传递一个复杂的对象作为查询参数。 代码举例如下:如何在router.navigate()中传递复杂对象作为Angular2中的查询参数

let navigationExtras: NavigationExtras = { 
    queryParams: { 
    "person": JSON.stringify({ 
     "firstname": "Mark", 
     "lastname": "Antony", 
     "address": { 
      "city": "San Francisco", 
      "state": "California" 
     } 
    }) 
    } 
} 

this.router.navigate([{outlets: {aux: 'user'}}], navigationExtras) 

...在接收端:

this.route.queryParams.subscribe(params => { 
    this.firsname = params["firstname"]; 
    this.lastname = params["lastname"]; 
}); 

导航时,URL已serailized作为字符串(编码)。所以有很多通配符出现在网址中。我想格式URL如下:

localhost:4200/main/(aux:user)?firstname=Mark&lastname=Antony&city=San Francisco&state=California 

有没有办法做到这一点?

回答

1

我不认为将整个对象作为QueryString传递是个好主意。 出于安全原因,因为使URL不那么有用。 我的建议是使用ID和服务来获取其他组件中的数据以检索数据或使用表单数据而不是查询字符串。 但是,如果你想使用查询字符串,你可以使用:

JSON.parse(text[, reviver])

JSON.stringify(value[, replacer[, space]])

您的要求是定制的,并根据自己的项目... 您可以覆盖的解析和字符串化方法建立串你喜欢的方式只要你遵循URL规则,你将不会有任何问题,如=>(aux:user) 圆括号不支持url格式。

JSON.stringfy=(data){ 
    //foreach property 
    //add format and for each nested property look for it's nested properties 
    //if your object has more nested property you can use recursive functions. 
    //you can use variable to detecting level or making object flat. 
} 

JSON.parse=()=>{ 
    ... 
} 
+0

感谢您的回答。我减少了准备通过url的对象的复杂性。现在它在发送端被串行化,并被传递给接收端的相关对象。 –

相关问题