繁体   English   中英

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

[英]How to get id from the URL using snapshot or ActivatedRoute subscriber in Angular?

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

credits/33/classes/20 only 20 or credits/33/classes/ only null("")

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

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

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

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

   console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));
}

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

const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: YourComponent }];

假设 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);
        }
      );
    }
}

创建一个路由,在该路由中将路由到您的组件,并将其添加到您的模块中。

const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: MyComponent },
{ path: 'credits/:id1', component: MyComponent }];

然后,您可以使用ActivatedRoute来获取您的参数。

 export class MyComponent implements {
  id1: string;
  id2: string;

  constructor(private route: ActivatedRoute) { 
    this.id1 = this.route.snapshot.params['id1'];
    this.id2 = this.route.snapshot.params['id2'];
  }

}

StackBlitz在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM