如何在Angular中获取路线参数?

时间:2019-08-28 14:07:40

标签: angular angular7 angular8

我的路线是:

const routes: Routes = [

  {
    path: "dictionary",
    component: AppComponent,
    children: [
      {
        path: ":dict",
        component: DictionaryComponent
      },
      {
        path: ":dict/:code",
        component: VersionsComponent
      }]
    }];

我查询网址http://localhost:4200/dictionary/dict/code

其中dict:dict参数,而code:code

AppComponent里面,我被束缚着听着:

export class AppComponent implements OnInit {
  ngOnInit() {
    this.activatedRoute.paramMap.subscribe(params => {
      console.log(params);
    });
  }

  constructor(private activatedRoute: ActivatedRoute) {

  }
}

但是我总是得到空对象:

console.log(params);

为什么当我使用此路线时它不起作用:

const routes: Routes = [
  { path: "login", component: LoginComponent },
  { path: "logout", component: LoginComponent },
  {
    path: "", component: AppComponent,
    children: [

      {

        path: "dictionary",
        component: AppComponent,
        children: [
          {
            path: ":dict",
            component: WordDictComponent
          },
          {
            path: ":dict/:code",
            component: VersionsComponent
          },
          {
            path: ":dict/:code/syncro",
            component: HistoryComponent
          },


        ]
      }
    ]
  },

];

如果删除path: "", component: AppComponent,,它将起作用

在stackBlitz中查看我的完整代码:

https://stackblitz.com/edit/angular-iitsn4

为什么我可以在根AppComponent中监听参数,但不能在DictionaryComponent中监听参数?

3 个答案:

答案 0 :(得分:4)

代码应放置在导航到的组件内部。 VersionsComponent就您而言

更新

如果要在App.component中获取参数,则需要这样做

在App.component.ts中添加此方法

  mergeRouteParams(router: Router): { [key: string]: string } {
    let params = {};
    let route = router.routerState.snapshot.root;
    do {
      params = { ...params, ...route.params };
      route = route.firstChild;
    } while (route);

    return params;
  }

然后在ngOnInit中执行此操作

    this.router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        console.log(this.mergeRouteParams(this.router));
      }
    });

当然还要将private router: Router添加到您的构造函数中

正在工作的闪电战

https://stackblitz.com/edit/angular-1dtfvr

检查https://angular-1dtfvr.stackblitz.io/dictionary/dict/code

的网址

enter image description here

答案 1 :(得分:1)

我从未使用过儿童路线,所以这是我的工作示例:

这些是我的路线,在您要导入到应用程序模块的“应用程序路由”模块中定义

const routes: Routes = [
  { path: '', component: MyComponent },
  { path: ':yourParam', component: MyComponent }
];

然后,在您的组件类中:

constructor(private myService: MyService, 
            private route: ActivatedRoute) {
}

  ngOnInit(): void {
    let param = null;
    if (this.route.snapshot.params.yourParam) {
       param = this.route.snapshot.params.yourParam;
    } ... do stuff with your param

答案 2 :(得分:-2)

  

this.activatedRoute.queryParams.subscribe(params => {          console.log(params);         }       });

     

使用queryParams代替paramMap