简体   繁体   English

Angular 6-绑定项目在数据更改后未更新

[英]Angular 6 - Binding item not updating after data change

In my HTML I am binding an item in a repeat: 在我的HTML中,我重复绑定一个项目:

<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: 但是现在该值正在API调用中更改,如下所示:

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 ,就像这样:

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. 所以我不知道我在API调用中是否做错了什么。

It seems like you need to refresh how JavaScript works. 似乎您需要刷新JavaScript的工作方式。 You are returning value = res.body value. 您正在返回value = res.body值。 But what's that? 那是什么 That won't even work. 那根本行不通。

It seems like items is array of objects which are reference types. 似乎items是引用类型的对象数组。 When you are trying to do value = res.body you are not changing anything inside items array at all. 当您尝试执行value = res.body您根本不会更改items数组内的任何内容。 You are just reassigning reference which is stored in value variable, but your item found with Array.find function is untouched. 您只是重新分配了存储在value变量中的引用,但是使用Array.find函数找到的项目保持不变。 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. 但是我不知道您的HttpResponse.body模型。 That's why you should response Promise<T> from service instead of HttpResponse<any> . 这就是为什么您应该从服务而不是HttpResponse<any>响应Promise<T>的原因。 You are using TypeScript, so make it useful! 您正在使用TypeScript,因此使其变得有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM