带多个参数的Angular 2路由器链接

Angular 2 Router Link with multiple parameters

本文关键字:路由器 链接 Angular 参数      更新时间:2023-09-26

我有一个这样的路由

   path: 'projects/:id/settings'

在我的header。component。html中我想有一个到这个页面的链接

<a routerLink="['projects', progectId,'settings']" routerLinkActive="active">cool link</a>

我有一个project.component,当我点击某个项目时,我进入项目页面。然后我需要有可能到达projects/:id/settings或其他类似的路线。

如何从projects.component传递progectId变量?
或者有人知道另一种实现方法

对于这种route,我有同样的问题,您应该像这样使用routerLink:

<a routerLink="/projects/{{progectId}}/settings" routerLinkActive="active">cool link</a>

并将route path更改为routing module,如下所示:

{ path: ':id/settings', component: YourComponent}

获取projectId的其他信息,您应该遵循以下步骤:

  1. component constructor中注入ActivatedRoute object
  2. component中定义variable称为projectId
  3. ngOnInit()方法中通过activatedRoute object获取params
  4. 最后你应该get projectId在你的html像这样:{{projectId}}

    import {Router, ActivatedRoute, Params} from '@angular/router';
    @Component({
      selector: 'app-your-component',
      templateUrl: './your-component.component.html',
      styleUrls: ['./your-component.component.css']
    })
    export class YourComponent implements OnInit {
      private projectId: string;
      constructor(private activatedRoute: ActivatedRoute) {}
      ngOnInit() {
         this.activatedRoute.params.subscribe((params: Params) => {
         this.projectId = params['id'];
      });
     }}
    

我通常在组件类中这样做

somefunctionName() {
    let link = ['/summary', this.param1, this.param2];
    this.router.navigate(link);
}

然后从html代码中调用函数,像这样

<a (click)="somefunctionName()">

在你的情况下,因为我假设你是循环通过你的项目,你可以调用你的函数与这样的参数

<a (click)="somefunctionName(pass the parameter here)">

然后更改函数定义以反映这一点。