角度|路由器不会重定向

时间:2020-03-13 18:11:11

标签: angular redirect angular-routing router

我已实现以下代码以重定向到我的温室植物

    <div *ngFor="let plant of plants" (click)="openPlant(plant)">
        <div class="row">
            <div class="col-md-3 p-l-0 p-r-0 my-auto">
                <img src="..." class="navbar-item-icon">
            </div>
            <div class="col-md-9 my-auto">
                {{plant.englishName}}
            </div>
        </div>
    </div>

(单击)openPlant:

  public openPlant(plant: PlantModel) {
    var foundPoor = this.checkIfPlantIsPoor(plant),
    this._generalService.openPlant(foundPoor, plant)
  }

_generalService openPlant:

  public openPlant(foundPoor, plant: PlantModel) {
    if (foundPoor) {
        ...
    } else {
        this.router.navigate(['desktop/plant/' + plant.id]);
    }
  }

因此,当我单击一个植物时,它将很好地重定向。但是在将其重定向到第一个工厂后,当我单击其他人时,浏览器中的url发生了变化,但它不会重定向到实际路线!只是在我点击的第一家工厂中。

因此,第一次进入http://localhost:4200/desktop/plant/2,然后单击以重定向到http://localhost:4200/desktop/crop/11,浏览器中的URL更改为http://localhost:4200/desktop/crop/11,但UI保持在http://localhost:4200/desktop/plant/2

这是我的app.routing

const routes: Routes = [
  ...
  { path: 'desktop', loadChildren: () => import('./pages/desktop/desktop.module').then(m => m.DesktopModule) },
  ...
];

这是台式机路由:

const routes: Routes = [
  ...
  { path: 'plant/:id', component: PlantComponent},
  ...
];

这里是PlantComponent:

HTML

<div class="container">
    <plant-item [plantID]=plantID></crop>
</div>

TS

  ngOnInit() {
    console.log(this.plantID)
    var _this = this
    var route = this.router.url
    this.plantID = this.activated_route.snapshot.paramMap.get("id")
  }

这是PlantItemComponent TS:

    ...
    this._plantService.currentPlants.subscribe(res => {
      this.activeSeed = this._plantsService.getMyActiveSeed(res, this.plantID)
      ...      
    })

在ngOnInit上,它将仅在我第一次导航到第一个Plant时console.log。当我单击导航至其他菜单时,它不会显示console.log。

这是一场关于路由以及我如何调用所需组件的堆叠闪电战:https://stackblitz.com/edit/angular-c9g1hl

1 个答案:

答案 0 :(得分:1)

这里的问题是,当您导航到相同的路线时,即使使用了不同的参数,Angular也会重新利用组件实例。这意味着您的ngOnInit函数仅被调用一次。我认为解决此问题的最简单方法是将ActivatedRoute视为可观察的结果:

ngOnInit() {
  console.log(this.plantID)
  var _this = this
  var route = this.router.url

  this.activated_route.params.subscribe(params => {
    this.plantID = params.id;
  });
}
相关问题