订阅时Angular 2更改数组值

时间:2019-01-03 13:44:52

标签: javascript arrays angular typescript

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

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 个答案:

答案 0 :(得分:4)

我认为是因为您没有在数组中设置新值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;
}

答案 1 :(得分:2)

据我了解,您的方法getProductsById()返回具有国家/地区字段的交易数组。如果我理解正确,则应使用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));

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

答案 2 :(得分:1)

您的 $scope.goid = function(eventid) { alert(eventid); $scope.userss = $resource('toostudentregister/'+eventid).query(function(data){return data;}) }; 仅在您的<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> </dependencies> 条件中是本地的。您只需要将值分配给变量属性本身即可。

因此,只需将行p替换为if 就可以了!