首页 > 解决方案 > Angular 7:如何在订阅中转换查询参数?

问题描述

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

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));
      });

地图(或我尝试过的任何其他转换)工作,但它下面的行不执行。我不知道问题是否与

我很感激任何关于正在发生的事情的建议。

标签: angularasynchronousrxjsquery-parameters

解决方案


我不确定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.


推荐阅读