将变量传递给 Angular routerLink

Pass variable to Angular routerLink

我现在的 URL:

http://localhost:4200/app/projects/ABC1/dashboards/5f6cc1e632acae2b16160123

我想要做的是当我点击一个按钮时,URL 变成 http://localhost:4200/app/projects/ABC1/dashboards/new

我正在尝试 routerLink

<button [routerLink]="['./projects/' + projectId + '/dashboards/new']">

但是我怎样才能用我在那个地方的变量替换 projectId

我还尝试将一个函数传递给 returns 以下

的 routerLink
public routeToCreateDashboard = (projectId: string): string => {
    return `./projects/${projectId}/dashboards/new`;
  };

但这也行不通。

对于字符串插值,这可能对您有所帮助:

// You can use String Interpolation this way

routerLink="/update/{{obj.id}}"

要在路由更改时添加事件,您可以使用路由器事件:

import {Injectable} from '@angular/core';
import {NavigationEnd, Router, RouterEvent} from '@angular/router';
import {filter, map} from 'rxjs/operators';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RouteEventService {
  constructor(private router: Router) {
  }

  subscribeToRouterEventUrl(): Observable<string> {
    return this.router.events
      .subscribe(  (event: RouterEvent) => {
                     if(event instanceof NavigationStart){

                     // console.log('Navigation Start', this.router.url);
                     }
          }

      );
  }
}