开发者问题收集

Angular 2 在订阅时更改数组值

2019-01-03
1728

我想在订阅数组后更改数组中的某些值。

this.data = this.search.getProductsById(this.id).subscribe
    ((data: any) => {
        this.list = data;
        //Here for each price I want to change price value 
        for (let entry of this.list.deals.new) {
            if (entry.country == 'UK') {
                let p = entry.price * 1.10837; //here I change price
                console.log(p); //displays new price
            }
        }
        this.loading = true;
    });

但在 HTML 中,它显示旧价格,而不是 p 。如何更改它以便在 html 中获取新价格?

3个回答

我认为这是因为你没有在数组中设置新值 p ,我认为它是这样的:

this.data =  this.search.getProductsById(this.id).subscribe
((data: any) => {
    this.list = data;
//Here for each price I want to change price value 
   for(let entry of this.list.deals.new){
     if(entry.country == 'UK'){
      entry.price *= 1.10837;
      console.log(entry.price); //displays new price
     }
   }
    this.loading = true;
}
B.Benjo
2019-01-03

据我了解,您的方法 getProductsById() 返回具有 country 字段的交易数组。如果我理解正确,您应该使用 map 运算符,如下所示

this.data = this.search.getProductsById(this.id)
.pipe(map((data: any) => {
  if (data.deals.country === 'UK') {
    return data.deals.price = data.deals.price * 1.10837;
  }
}))
.subscribe(data => console.log(data.deals.price));

为了更好地理解,请给我们返回对象的结构

Roman Lytvynov
2019-01-03

您的 p 仅在类中的 if 条件中是本地的。您只需将值分配给变量属性本身即可。

因此,只需 将行 let p = entry.price * 1.10837; 替换为 entry.price = entry.price * 1.10837; 即可!

Tushar Walzade
2019-01-03