manneJan89
manneJan89

Reputation: 1024

Angular 6 - Binding item not updating after data change

In my HTML I am binding an item in a repeat:

<ul *ngFor="let item in items">
    <li>{{ item.id }}</li>
</ul>

This is working fine. But now that value is being changed in an API call, like so:

doApiCall(){
    let value = this.items.find( x => x.id = '123');
    this.service.doIt().subscribe(
        (res: HttpResponse<myModel>) => {
            // response === { id = 456' }
            return value = res.body;
        }
    )
}

now the item in the array has changed, but the view does not change. But the funny thing is, if I change the let value manually right after it is set, like so:

let value = this.items.find( x => x.id = '123');
value.id = '345'

then the update happens. So I do not know If I am doing something wrong in the API call.

Upvotes: 0

Views: 2878

Answers (1)

web.dev
web.dev

Reputation: 359

It seems like you need to refresh how JavaScript works. You are returning value = res.body value. But what's that? That won't even work.

It seems like items is array of objects which are reference types. When you are trying to do value = res.body you are not changing anything inside items array at all. You are just reassigning reference which is stored in value variable, but your item found with Array.find function is untouched. Maybe you should try doing something like

doApiCall() {
    let value = this.items.find(x => x.id = '123');
    this.service.doIt().subscribe(
        (res: HttpResponse < any > ) => {
            value.id = res.body.id;
            value.someproperty = res.body.property;
        }
    )
}

But I don't know your HttpResponse.body model. That's why you should response Promise<T> from service instead of HttpResponse<any>. You are using TypeScript, so make it useful!

Upvotes: 4

Related Questions