【问题标题】:Angular 7: How to transform query params within subscription?Angular 7:如何在订阅中转换查询参数?
【发布时间】:2019-09-09 15:39:50
【问题描述】:

我想在订阅中将查询参数转换为整数,但由于某种原因,将查询参数转换为整数(或任何其他类型)之后的代码会导致代码停止执行。

combineLatest(params, queryParams, (params, qparams) => ({ params, qparams }))
      .subscribe(allParams => {
        this.item.color = allParams.qparams['color'] || allParams.params['color'] || ''; //this line must be above
        this.item.price = parseInt(allParams.qparams['price']) || 0; //this line also
        this.items.features = allParams.qparams['features'].map(feature => parseInt(feature));
      });

Map(或我尝试过的任何其他转换)工作,但它下面的行不执行。不知道是不是跟问题有关

  • 使用数组(features 是一个数组);
  • 在异步中调用同步函数(映射);
  • 完全不同。

对于正在发生的事情的任何建议,我将不胜感激。

【问题讨论】:

  • 能否添加执行这段代码时抛出的错误?
  • 没有显示错误,我是在每行下面添加console.log后才看到的。
  • 你能console.log(allParams)和我们分享输出吗?
  • params 是什么? queryParams 是什么?请分享更多代码。与简单订阅 ActivatedRoute 相比,combineLatest 在您的代码中有什么好处?
  • 它是URL参数和查询参数(用于保持数据刷新)

标签: angular asynchronous rxjs query-parameters


【解决方案1】:

我不确定combineLatest 的使用在您的场景中是否多余。我什至会跳起来说这是你的问题,因为combineLatest 将等待它提供的所有可观察对象发出一个初始值(从你的代码来看,这似乎不会发生)。 我会做这样的事情:

constructor(route: ActivatedRoute)  {}

ngOnInit(): void {
    this.item.color = '';
    this.item.price = 0;
    this.item.features = [];
    this.route.queryParams.subscribe(queryParams => {
       this.item.color = queryParams['color'] || '';
       this.item.price = queryParams['price'] || 0;
       this.item.features = queryParams['features'].map(feature => parseInt(feature));
    });

    // ...Do the same with this.route.params
}

如果你想使用combineLatest,但不想被动地等待初始值,你可以用.pipe(startWith(null)) 管道化一个:

combineLatest(params.pipe(startWith(null)), queryParams.pipe(startWith(null)), (params, qparams) => ({ params, qparams })) ....

或者...您可以使用zip 代替combineLatest

【讨论】:

  • 但是我还需要获取参数(不仅仅是查询参数),有没有办法做到这一点?如果我不考虑这些转换方法,一切都会完美无缺。等待初始值非常有趣,谢谢!以后我会记住的。
  • @Mandy 请参阅我对 combineLatest 用法的编辑。这可能会解决您的问题
  • 非常感谢,我会尽力告诉你的!再次感谢!
  • 不幸的是,它没有用。在这种情况下,Zip 的工作方式与 combineLatest 相同,而其他方法根本不起作用。我一定错过了什么,但不知道是什么。只是想让你知道,谢谢你的好意和时间!
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 2021-10-06
相关资源
最近更新 更多