【问题标题】:Angular 8 sending an array with the navigate() is returning an object instead of the array itselfAngular 8 发送一个带有 navigate() 的数组是返回一个对象而不是数组本身
【发布时间】:2019-08-23 20:34:28
【问题描述】:

我想在 Angular 8 路由模块的.navigate() 内发送一组数据。

在home组件中,结果:

console.log(this.offers)

正在返回所有可用的优惠及其所有相关数据。

之后,我在导航中发送this.offers

this.router.navigate(['/offers'], {queryParams:{ 'offers': this.offers}});

在优惠组件中,我尝试使用以下方法获取优惠数组:

console.log(this.activatedRouter.snapshot.queryParams.get('offers'))

但结果只是[Object Object]

我尝试使用this.activatedRouter.snapshot.params['offers'],但返回的结果相同。

我尝试了以下方法:

console.log(this.activatedRouter.snapshot.queryParamMap.get('offers'))

但它返回了一个 [Object Object]:

【问题讨论】:

  • 查询参数是字符串,在 URL 的查询字符串中:offers?foo=bar&baz=bing。尝试将 JavaScript 对象放入查询参数中没有多大意义。
  • @JbNizet 那么用什么代替呢?
  • 什么都没有。只需导航到组件,并让组件加载所有可用的商品(如果需要显示它们)。
  • 我使用window state找到了解决方案

标签: angular angular-router angular8 angular-activatedroute


【解决方案1】:

不要使用activatedRouter.snapshot,而是订阅this.activatedRoute.queryParams 流,它会主动发出查询参数的任何更改。

@Component({ ... })
export class MyComponent implements OnInit {
  order: string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.queryParams
      .filter(params => params.offers)
      .subscribe(params => {
        console.log('Query Params: ', params); // {offers: <value>}
      });
  }
}

【讨论】:

  • 可以使用 Params 代替 queryParams 吗?
【解决方案2】:

根据媒体上的this link,有几种解决方案。

我需要的是使用this.navigate

所以解决方案是在原始组件中:

this.router.navigate(['/offers'], { state: {'offers': this.offers, 'info': this.info}});

在我的情况下不是子组件的目标组件(它可以,没问题),我们应该使用 state 附加组件,它是 Angular 7.2+ 的新组件:

this.offers = window.history.state.offers;

在这种情况下我们不能使用snapshotqueryParams,因为根据上面的链接,它会在ngOnInit()执行后被删除。所以最好的解决方案是使用state extra

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2016-05-03
    • 2019-05-18
    • 2020-05-06
    • 2020-10-07
    • 1970-01-01
    • 2016-03-06
    相关资源
    最近更新 更多