【问题标题】:How to pass and get parameter with routerLink in Angular 2?如何在Angular 2中使用routerLink传递和获取参数?
【发布时间】:2017-02-13 10:22:42
【问题描述】:

我想使用 routerLink 传递一个带有 url 的值。并在另一页上阅读该值。 就像我有产品清单一样。在选择第一条记录时,该记录的 ID 传递到产品详细信息页面。阅读该 productId 后,我想显示该产品的详细信息。

那么如何传递和获取参数呢?

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    我假设你有一些这样的代码:

    { path: 'product/:id', component: ProductDetailComponent }
    

    在产品列表模板中

    <a [routerLink]="['/product', id]">Home</a>
    

    <a [routerLink]="['/product', 5]">Home</a>
    

    id 是一个变量,也许你在循环中得到它。

    在 ProductDetailComponent 中:

    constructor(
      private route: ActivatedRoute,
      private router: Router
    ) {}
    ngOnInit() {
    
      this.route.params
        // (+) converts string 'id' to a number
        .switchMap((params: Params) => this.yourProductService.getProductById(+params['id']))
        .subscribe((product) => this.product = product);
    }
    

    路由器文档:https://angular.io/docs/ts/latest/guide/router.html

    【讨论】:

    • 我得到错误 Property 'switchMap' does not exist on type 'Observable' 。
    【解决方案2】:

    在您的a 标签上使用routerLink 通过url 传递它。

    [routerLink]="['yourRouteHere', {'paramKey': paramValue}]
    

    要获得它,您需要使用ActivatedRoute 服务。将其注入您的组件并使用它的 subscribe 方法。这里我的route注入的服务

    this.route.params.subscribe(params => {
       const id = Number.parseInt(params['paramKey']);
    }
    

    如果你想从路由段获取参数,使用.params,否则如果你想从查询字符串,使用.queryParams

    【讨论】:

    • 但是[routerLink]="['yourRouteHere', {'paramKey': {'key':'value'}}]
    • @suren 添加双引号[routerLink]="['yourRouteHere', {'paramKey': paramValue}]"
    • 这个解决方案更好,因为您不需要创建任何新路径!
    【解决方案3】:

    试试这个:

    Step-1:在路由模块中

    { path: 'product/:id', component: ProductDetailComponent }
    

    步骤 2:将值发送到路由

    <a [routerLink]="['/product', id]">Home</a> //say, id=5
    

    Step-3:读取 ProductDetailComponent 中的值

    首先从'@angular/router 注入ActivatedRoute 并说route 是注入的服务。使用ngOnInit()方法中的以下代码来阅读它。

    id = this.route.snapshot.paramMap.get('id');
    

    【讨论】:

      【解决方案4】:
      1. 假设您的网址是 http://mit.edu/dashboard 并且期望的结果是 http://mit.edu/dashboard/user?id=1 然后使用下面的代码
      <a [routerLink]="['user']" [queryParams]="{id: 1}" </a>
      
      1. 假设你的 url 是 http://mit.edu/dashboard 并且你想要的结果是 http://mit.edu/user?id=1 然后使用下面的代码 ["Difference is /Dashobard"网址中缺少这里]
      <a [routerLink]="['/user']" [queryParams]="{id: 1}" </a>
      

      【讨论】:

        【解决方案5】:

        你可以在.html使用这个

        [routerLink]="['/trips/display/' + item.trip, {'paramKey': 'application'}]"
        

        .ts 中,您可以使用它来恢复参数

        this.id = this.route.snapshot.params['id'];
        const param = this.route.snapshot.params['paramKey'];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-16
          • 2018-06-26
          • 2017-05-20
          • 1970-01-01
          • 2016-10-19
          • 1970-01-01
          • 2017-01-20
          • 1970-01-01
          相关资源
          最近更新 更多