2

I want to change some values in an array after I subscribe to it.

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

But in HTML it displays old price, not p. How to change it so I would get in html new one ?

5
  • Can you add your html code? Commented Jan 3, 2019 at 13:46
  • 2
    Your example doesn't show you aren't updating the price. By using let you are creating a new variable and aren't assigning it to anything. Changing the value would be done by doing something like entry.price = entry.price * 1.10837; Commented Jan 3, 2019 at 13:47
  • Sure, will edit right now. Commented Jan 3, 2019 at 13:47
  • Oh... Sorry for dumb question, really messed up... ;D Commented Jan 3, 2019 at 13:49
  • As @AndrėjusLazauskas said, you are just changing it locally. Commented Jan 3, 2019 at 13:49

3 Answers 3

4

I think it's because you didn't set the new value p in your array, i think it's like this:

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes... Sometimes just dumb mistakes.. Sorry.
2

As I understand, your method getProductsById() return an array of deals which have country field. If I understand correctly, you should use map operator something like this

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

For better understanding give us the structure of the returned object

Comments

1

Your p is local to your if condition in a class only. You simply need to assign the value to the variable property itself.

So, just replace the line let p = entry.price * 1.10837; with entry.price = entry.price * 1.10837; That's it!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.