【问题标题】:Angular | Router won't redirect角 |路由器不会重定向
【发布时间】:2020-06-25 18:12:49
【问题描述】:

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

    <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>

(点击)打开Plant:

  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) },
  ...
];

这里是 desktop.routing:

const routes: Routes = [
  ...
  { path: 'plant/:id', component: 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 上,它只会在我第一次导航到第一个工厂时 console.log。当我点击导航到其他人时,它不会 console.log。

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

【问题讨论】:

  • 你能分享你的路线定义吗
  • 请分享 Stackblitz 以追踪您的错误。
  • @RahulTokase 用更多代码和堆栈闪电更新了我的答案。感谢您的宝贵时间!

标签: angular redirect angular-routing router


【解决方案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;
  });
}

【讨论】:

  • 是的,我已经这样做了,希望有更好的解决方案,但它仍然有效。感谢您的努力:D
猜你喜欢
  • 2021-09-09
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多