包含路径参数的角度路径路径供组件使用

问题描述

我正在尝试实现一个 Angular 组件,它可以从 url 中提取路径参数,即 /update-tap/some-url-path-param-to-be-extracted。我认为实现这一点的正确方法是在带有一些正则表达式的路由模块中,但这不起作用。这是我的app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule,Routes } from '@angular/router';
import { BeerEditorComponent } from './beer-editor/beer-editor.component';
import { BeerListComponent } from './beer-list/beer-list.component';
import { TapUpdaterComponent } from './tap-updater/tap-updater.component';

const routes: Routes = [
  {path: '',redirectTo: 'beer-list',pathMatch: 'full'},{path: 'beer-list',component: BeerListComponent},{path: 'create-beer',component: BeerEditorComponent},{path: 'update-tap/*',component: TapUpdaterComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],exports: [RouterModule]
})
export class AppRoutingModule { }

解决方法

在你的 ngOnInit 方法中编写代码如

this._route.params.subscribe(params => {
    const action = params['myParam'];
};

更新以下路线 -

{path: 'update-tap/*',component: TapUpdaterComponent}

{path: 'update-tap/:myParam',component: TapUpdaterComponent}

在组件构造器中

constructor(public _route: ActivatedRoute){ 
}