【问题标题】:Router Parameter in Angular2Angular2中的路由器参数
【发布时间】:2016-03-17 05:42:30
【问题描述】:

问题是路由器参数显示在 URL 中,而我希望我的路由器参数不显示在 URL 中?

myComponent.ts

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

])

我的组件.html

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

【问题讨论】:

  • 我认为最好的方法是使用 sharedService !
  • 能否如您所说的那样解释一下如何使用共享设备,如果您提供示例对我们来说会更好。

标签: angular angular2-routing


【解决方案1】:

到目前为止,sharedService 可能是最后一个选项,因为您不想在 url 中显示数据。 RouteData 可以是一个选项,但它是 immutable。 请仔细阅读这两个主题。

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

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

【讨论】:

    【解决方案2】:

    如果您想通过路由发送静态值作为参数,那么您可以通过 angular2 中路由的data 属性发送,使用 URL 中未显示的此参数。

    基本上有两种选择(据我所知)通过路由发送数据

    • RouteParams          (如所讨论的那样)
    • data(RouteData)     (路由时的属性)

    路由参数

    现在,当我们使用RouteParams 发送数据时,我们必须以类似的方式定义:

    {path: '/editUser/:userId', name: 'Edit User', component: UserEditComponent}
    
    <a href="#" [routerLink]="['Edit User',{userId: id}]"
    

    通过使用这种方法,我们可以正常发送数据,但所有数据都在 URL 中可见

    数据

    当我们不想在 URL 路径中显示数据时,我们必须使用 angualr2 提供的 @RouteConfig annotationdata 属性通过路由发送数据。通过使用此属性,我们可以在路由配置时向组件发送附加数据,而无需在 URL 中显示。这是此属性的示例。

    @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'));
        }
    }
    

    通过使用它,我们可以通过路由发送数据而不显示在 URL 中。

    Plunker - working example of the same

    更多信息请阅读awesome artical

    【讨论】:

      猜你喜欢
      • 2017-12-03
      • 2017-04-17
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      相关资源
      最近更新 更多