【问题标题】:Why do they loop on route parameters in this Angular tutorial?为什么他们在这个 Angular 教程中循环路由参数?
【发布时间】:2017-02-17 12:04:51
【问题描述】:

我正在查看Angular 2 tutorial about routing。在某些时候,他们添加了一个路由/detail/:id 并添加了一个ngOnInit() 方法来处理这个路由,特别是获取:id 参数:

ngOnInit(): void {
  this.route.params.forEach((params: Params) => {
    let id = +params['id'];
    this.heroService.getHero(id)
      .then(hero => this.hero = hero);
  });
}

我不明白的部分是他们为什么在路由参数上循环?既然只能有一个ID,是不是不能用this.route.params['id']得到呢?

另外,如果真的有多个 id,那么循环它们有什么意义,因为每个新英雄只会替换前一个?

【问题讨论】:

  • 我认为它不会通过参数循环。

标签: angular typescript routes


【解决方案1】:

当路由以仅参数更改的方式更改(例如/somepath/:id/otherPath 中的id)时,路由器不会导航离开并返回相同的组件,而是保留相同的组件并发出参数更改事件。

对于每个事件 (params:Params) => { ... } 都会执行。

【讨论】:

    【解决方案2】:

    现在您可以这样做: 首先从rxjs导入switchMap

    import 'rxjs/add/operator/switchMap';
    

    然后

    this.route.params
        .switchMap((params: Params) => this.heroService.getHero(+params['id']))
        .subscribe(hero => this.hero = hero);
    

    【讨论】:

      【解决方案3】:

      首先,你在这里使用的 forEach() 方法不是 Array.prototype.forEach() 而是它的 Rx.Observable.prototype.forEach()。

      Angular 2 route.params - 给出一个 Observable 数组。使用 lambda 在 this 数组上调用 forEach() 与调用 subscribe 的每个参数相同。

      订阅参数背后的进一步原因是,当一个组件从其他组件路由或刷新时会调用 ngOnInit()。如果参数中的值未订阅,则如果您路由到具有不同参数值的同一组件,它将不起作用,因为在这种情况下不会调用 ngOnInit。

      请参考 the Rx.Observable.prototype.forEach

      【讨论】:

        【解决方案4】:

        要检索单个Id,您也可以使用它,

        let id = +this.route.snapshot.params['id'];
        

        【讨论】:

          【解决方案5】:

          您现在可能已经知道这一点,但我认为您需要了解的概念是 params 不是一个数组,它是一个 Observable。

          console.log(this.route.params['id']); // undefined
          this.route.params.forEach(x => console.log(x['id'])); // the id e.g 999
          

          正如其他人所提到的,有多种获取 id 的方法,只是在使用快照时要小心,因为在重用组件时它不会更新。

          【讨论】:

            猜你喜欢
            • 2015-10-15
            • 1970-01-01
            • 1970-01-01
            • 2021-03-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多