【问题标题】:How can I programmatically pass parameters to an auxiliary route in angular2+?如何以编程方式将参数传递给角度 2 中的辅助路线?
【发布时间】:2017-06-17 14:20:20
【问题描述】:

使用 angular2,我想在我的组件中以编程方式打开一个辅助路由。

此代码使用“列表”路径打开路由,并在正确命名的路由器出口中打开路由,但我不确定如何将参数传递给路由:

this.router.navigate(['./', { outlets: { 'list-outlet': 'list' } }]);

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    显示特定产品详细信息的组件的路由需要该产品的ID 的路由参数。我们可以使用以下路由来实现这一点:

    export const routes: Routes = [
      { path: '', redirectTo: 'product-list', pathMatch: 'full' },
      { path: 'product-list', component: ProductList },
      { path: 'product-details/:id', component: ProductDetails }
    ];
    

    注意:idproduct-details路由的路径中,将参数放在路径中。例如,要查看带有 ID 5 的产品的 product-details 页面,您必须使用以下 URL:localhost:3000/product-details/5 使用参数链接到路由

    ProductList 组件中,您可以显示产品列表。每个产品都会有一个指向product-details 路由的链接,传递产品的ID

    <a *ngFor="let product of products"
      [routerLink]="['/product-details', product.id]">
      {{ product.name }}
    </a>
    

    请注意,routerLink 指令传递一个指定路径和路由参数的数组。或者,我们可以以编程方式导航到路线:

    goToProductDetails(id) {
      this.router.navigate(['/product-details', id]);
    }
    

    ProductDetails组件必须读取参数,然后根据参数中给出的ID加载产品。 ActivatedRoute 服务提供了一个params Observable,我们可以订阅它来获取路由参数(参见 Observables)

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
      selector: 'product-details',
      template: `
        <div>
          Showing product details for product: {{id}}
        </div>
      `,
    })
    export class LoanDetailsPage implements OnInit, OnDestroy {
      id: number;
      private sub: any;
    
      constructor(private route: ActivatedRoute) {}
    
      ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
           this.id = +params['id']; // (+) converts string 'id' to a number
    
           // In a real app: dispatch action to load the details here.
        });
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
    

    ActivatedRoute 上的params 属性是 Observable 的原因是路由器在导航到同一个组件时可能不会重新创建该组件。在这种情况下,参数可能会更改而无需重新创建组件。

    Plunkr example

    来自here的信息

    【讨论】:

    • 感谢您的回复...参考您上面的“goProductDetails()”函数,如果路由位于命名路由或辅助路由中,我将如何实现?例如,我的路由器(目前可以工作,但没有数据是:this.router.navigate(['./', { outlets: { 'list-outlet': 'list'} }]);
    • 我也面临类似的问题
    【解决方案2】:

    最后,我只需要使用一个数组来传递我的参数...参见下面的param1param2

    this.router.navigate(['./', { outlets: { 'list-outlet': ['list', param1, param2]} }]);
    

    注意...我必须更改路由配置中的路径:

    {
        path: 'list/:param1/:param2',
        component: ClaimListComponent,
        outlet: 'list-outlet'
    }
    

    然后在我的ngOnInit 函数中,我可以将参数从路由器中拉出,如 Muirik 所示。

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      相关资源
      最近更新 更多