Router Parameter in Angular2

老子叫甜甜 提交于 2019-12-12 03:36:58

问题


The problem is that router parameters are showing in URL while I want my router parameter not to show in URL ?

myComponent.ts

@RouteConfig([      
        { path: '/routerOne/:myId', component: routerOne, name: "routerOne",useAsDefault: true},
        { path: '/routerTwo/:myId', component: routerTwo, name: "routerTwo"},

])

myComponent.html

  <a [routerLink]="['routerOne',{myId:this.Id}]">RouterOne</a>
  <a [routerLink]="['routerTwo',{myId:this.Id}]">routerTwo</a>

回答1:


As of now sharedService can be the last option as you don't want to show data in url. RouteData can be an option but it is immutable. please read this two threads carefully.

https://github.com/angular/angular/issues/6672

https://github.com/angular/angular/issues/6569




回答2:


If you want to send static value via routing as parameters then you can send via data property of routing in angular2 by using this parameters does't show in the URL.

Basically There are two options (upto my knowledge) to send data via routing

  • RouteParams          (as used in question)
  • data(RouteData)     (property at the time of routing)

RouteParams

Now when we send data using RouteParams we have to define in the similer way like this:

{path: '/editUser/:userId', name: 'Edit User', component: UserEditComponent}

<a href="#" [routerLink]="['Edit User',{userId: id}]"

By using this method we send data normaly but all data is visible in the URL

Data

when we don't want to show data in the URL path than we have to send data via routing using data property of the @RouteConfig annotation provided by angualr2. by using this property we can send additional data to the components at the time of the route configuration without showing it in the URL. here is example of this property.

@RouteConfig([
    {path: '/product/:id', component: ProductDetailComponentParam,
     as: 'ProductDetail', data: {isProd: true}}])

export class ProductDetailComponentParam {
    productID: string;
    constructor(params: RouteParams, data: RouteData) {
        this.productID = params.get('id');

        console.log('Is this prod environment', data.get('isProd'));
    }
}

by using this we can send data via routing without showing in the URL.

Plunker - working example of the same

for more info read this awesome artical



来源:https://stackoverflow.com/questions/36052495/router-parameter-in-angular2

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