可以在 Angular 中路由之前使用查询参数记录路由

Possible to log a route with query parameters before routing in Angular

我必须在 Angular 2.4 中使用 typescript 的应用程序重新路由。重新路由通过按下按钮发生。各自的代码如下:

component.html

<button class="btn btn-lg btn-primary" (click)="negotiation()"
                            [disabled]="!negotiationEnable"
                            [hidden]="!hiddenElement">
                        Rerouting Button
</button>

component.ts

negotiation(): void {
        // == Console.log this path with parameters here.. ==
        this.router.navigate(['/simple-search-details'],
            { queryParams: {id: this._negotiation_id, catalogueId: this._negotation_catalogue_id} });
    }

问题在于需要在应用程序中重新路由的 URL 仍在开发中,但是很高兴知道 link 与查询参数的外观和 URL.

如果我执行 console.log(this.router.navigate(...)) 命令,它确实会产生错误。

预期结果

/simple-search-details?catalogueId=blah-foo-1bar&id=some-text-id

使用路由守卫。允许导航,显示 url,进一步停止导航

import {CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';

@Injectable()
export class AuthGuardService implements CanActivate {

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    alert(state.url);
    return false;
  }

}

在该组件的 constructor() 中,为导航事件添加侦听器:

import { Router, NavigationStart } from '@angular/router';

constructor (private _router: Router) {
  _router.events.subscribe(event => {
    if(navigationEvent instanceof NavigationStart) {
      console.log(navigationEvent.url);
    }
  })
}

NavigationStart 事件使用了一个接口,该接口提供了一个路由 ID,URL 的参数被值替换。

在我的例子中,对于定义为 /part/:id 的路由,它记录 /part/123。我假设它会根据您使用的任何路由策略重写输出。