【问题标题】:Dynamic Routing with IDs not rendering Recent Angular Component带有 ID 的动态路由不呈现最近的 Angular 组件
【发布时间】:2021-04-01 01:38:53
【问题描述】:

我无法导航到具有 ID 的不同动态项目。解释:

app.component.html

<mat-sidenav-container>
    <mat-sidenav  mode="side" opened="true">
      <mat-nav-list>
         <a mat-list-item routerLink="home" >Home</a>
         <a mat-list-item routerLink="item/1" >Item 1 </a>
         <a mat-list-item routerLink="item/2" >Item 2 </a>
         <a mat-list-item routerLink="item/3" >Item 3 </a>
      </mat-nav-list>
    </mat-sidenav>
    <div class="container">
      <router-outlet></router-outlet>
    </div>
    </mat-sidenav-container>

app-routing.module.ts

export const routes = [
  { path: "home", component: HomeComponent },
  { path: "item/:id", component: AccountsComponent }
];

帐户组件

export class AccountsComponent  {
 constructor(private activatedRoute: ActivatedRoute,private router:Router) {}
 public id: string;
 ngOnInit() {
 this.id = this.activatedRoute.snapshot.paramMap.get('id');
 console.log("ID",this.id,"Route",this.router.url); 
   }
}

要检查当前的动态 id,我在我的 AccountsComponent 控制台中打印 url 参数,如上所述。现在,如果我在路由 'localhost:4200/home' 上并单击 Item1,我会被路由到 'localhost:4200/item/1',并且 AccountsComponent 会加载到我的 sidenav 中,这与预期的一样!在我的控制台中,ID 1 Route /item/1 也会被打印出来。现在如果我点击 Item2,上面显示的路线是 'localhost:4200/item/2' 但我的 sidenavcontent 即 AccountsComponent 不刷新!此外,我的控制台没有显示更新,即 ID2 没有打印出来。

我注意到,由于动态 url 确实指向同一个组件,路由器模块不会再次加载该组件。当我从Home-&gt;Item1-&gt;Home-&gt;Item2 移动时,它发生得很好,因为路由home 有一个不同的组件要加载。请参阅下面的 stackblitz 链接。

附: -

  1. Stackblitz链接
  2. 请不要建议为不同的ID使用不同的组件,这只是我复杂问题的一个更简单的原型

谢谢:)

【问题讨论】:

  • 这就是为什么Angular建议使用this.route.paramMap.pipe(switchMap来获取当前参数

标签: angular routes url-routing angular-routing angular10


【解决方案1】:

您的路由器工作正常。您应该订阅更改路由参数。
更新ngOnInit如下


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

【讨论】:

  • 谢谢。你能解释一下为什么当我必须从 Home 切换到 Item1 等等时我不需要这个吗?
  • 如果您关注 Home->Item1->Home->Item2->home->Item3,您将看到预期的日志。当您尝试直接从一个 Item 转到另一个 Item 时,不会重新调用 ngOnInit,因为您在同一个组件上。在这个答案中,您正在订阅路由参数,因此每当死记硬背的参数发生变化时,都会调用 subscribe 中的回调
猜你喜欢
  • 2018-08-03
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 2017-07-21
  • 2018-10-13
相关资源
最近更新 更多