如何在 Angular 中使用快照或 ActivatedRoute 订阅者从 URL 获取 id?

Rah*_*mov 3 angular angular-router angular-activatedroute

我使用快照方法获取价值,但在这种情况下它在“类”之后获取价值 20 但我需要 33 路径,如获取

credits/33/classes/20 only 20 or credits/33/classes/ only null("")
Run Code Online (Sandbox Code Playgroud)

更新:我找到了我的问题的解决方案。

现在它正在正确获取 id。错误是访问了右子组件中的元素,在 Snapshot 版本中的子组件 MatDialog 组件中不起作用。

constructor(private route: ActivatedRoute) {} 
 ngOnInit(): void {
   console.log(parseInt(this.route.snapshot.paramMap.get('id1')));
Run Code Online (Sandbox Code Playgroud)

如果您的 url 有 2 个 Id 值,则可以使用 route.parent 的快照

   console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));
}
Run Code Online (Sandbox Code Playgroud)

Nas*_*tad 11

您在路由模块中的路径将是

const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: YourComponent }];
Run Code Online (Sandbox Code Playgroud)

假设 id1 是 33,id2 是 20

代码将是: 使用 ActivatedRoute 而不是 ActivatedRouteSnapshot

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {

ngOnInit() {
this.route.params
      .subscribe(
        (params: Params) => {
          this.id1 = +params['id1'];
          this.id2 = +params['id2'];
          console.log(id1 + '' + id2);
        }
      );
    }
}
Run Code Online (Sandbox Code Playgroud)