角度5路由到相同的组件但不同的参数,不工作

ala*_*yab 13 navigation routing angular

我有角度5基本的初级应用程序,只有5个组件

我的路由和链接看起来像这样

//copied from app.module.ts
const appRoutes:Routes = [
  {path:'',component:HomeComponent},
  {path:'items/:cat',component:ItemsComponent},
  {path:'itemdetail/:id',component:ItemdetailComponent},
  {path:'settings',component:SettingsComponent},
];

//copied from navbar.component.html
<ul>
      <li><a [routerLink]="['/']">Home</a></li>
      <li><a [routerLink]="['/items/8']">Rashion</a></li>
      <li><a [routerLink]="['/items/2']">Vegitables</a></li>
      <li><a [routerLink]="['/items/3']">Fruits</a></li>
      <li><a [routerLink]="['/items/7']">Other</a></li>
      <li><a [routerLink]="['/items/5']">Sweets</a></li>
      <li><a [routerLink]="['/settings']">Settings</a></li>          
</ul>

//copied from items.component.ts
ngOnInit(){
    this.cat = this.route.snapshot.params['cat'];
    this.itemsSrv.getItems(this.cat)
            .subscribe((data)=>{
                this.items=data;
            });
}
Run Code Online (Sandbox Code Playgroud)

链接仅在它转到不同的组件时才起作用,
意味着我可以从主页导航到/items/2
但是当我在项目组件中时我可以导航到/items/any-parameter
虽然从项目我可以转到主页或设置组件.
简而言之,即使参数不同,它现在也在努力导航到相同的组件. 在此输入图像描述

我注意到一件事,URL正在改变,但页面内容与旧页面没有重新加载新网址相同:(

小智 13

所以,最好的办法是使用订阅路线:

userSubscription: Subscription;
...
ngOnInit() {
   this.userSubscription = this.route.params.subscribe(
            (params: Params) => {
                 //------ some code -----
   })
}
Run Code Online (Sandbox Code Playgroud)

之后,您必须取消订阅:

ngOnDestroy(): void {
        this.userSubscription.unsubscribe()
}
Run Code Online (Sandbox Code Playgroud)


Hom*_*oco 5

我知道这有点晚了,但我遇到了同样的问题并找到了解决方案。您正在this.route.snapshot.params用来获取id参数。根据Angular文档,仅在组件实例永远不会被重用时才使用快照。快照仅提供路由参数映射的初始值,并且在重用组件时不会更新。这意味着,如果您通过id路由到某个组件,然后(在显示该组件时)尝试路由到具有不同id的同一组件的新实例,则初始组件将被重用,但数据不会更新,因为ngOnInit()不被称为第二次。

要解决此问题,您必须进行更改;

this.cat = this.route.snapshot.params['cat'];
Run Code Online (Sandbox Code Playgroud)

使用这种格式;

ngOnInit() {
  this.cat$ = this.route.paramMap.pipe(
    switchMap((params: ParamMap) =>
      this.itemsSrv.getItems(params.get('id')))
  );
}
Run Code Online (Sandbox Code Playgroud)

this.route.paramMap从可观察到其返回

“暗示路由参数图可以在该组件的生存期内更改”。

您可能必须修改代码的其他部分才能使用Observable(cat $),但是由于我只能看到部分代码,因此我不建议其他更改。在下面的文档中,里程碑3末尾有一个项目文件(hero-detail.component.ts),显示了其工作原理。

您可以在此处阅读官方文档。

Angular2 +可观察的paramMap和组件重用

希望这对您有所帮助,并祝您编程愉快!


Dan*_*pel 3

当您导航到同一组件时,Angular 不会重新触发您的ngOnInit()方法。为了让你的代码正常工作,你需要使用route可观察的参数版本并订阅其更改。请务必阅读有关路由的 Angular 文档。他们那里有很多有用的信息。

ngOnInit(){
    this.route.paramMap
        .switchMap(params => this.itemsSrv.getItems(params.get('cat')))
        .subscribe(data => {
            this.items=data;
        });
}
Run Code Online (Sandbox Code Playgroud)

当您离开此组件时,您需要确保取消订阅此订阅。以下是关于如何做到这一点的最佳实践的讨论。