HttpClient中的角度变化检测 [英] Angular Change Detection in HttpClient

查看:69
本文介绍了HttpClient中的角度变化检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HttpClient 服务,该服务正在后端更新数据.在后端处理期间,我通过执行 this.isLoading = true 显示加载状态,在成功处理之后,我正在 subscribe()中删除该加载状态.使用 this.isLoading = false; .

I have an HttpClient service which is updating the data at backend. During the processing at backend, I' am displaying a loading state by doing this.isLoading = true, and after the successfully processing, I' am removing that loading state in subscribe() by using this.isLoading = false;.

现在,我将代码更改为使用 ChangeDetectionStrategy.OnPush ,并且加载状态不再消失.我知道 ChangeDetectionStrategy.OnPush 中的更改检测是在更改 input 属性或在组件等事件期间更改对象引用时发生的.

Now I changed my code to use ChangeDetectionStrategy.OnPush and the loading state is not vanishing anymore. I know the change detection in ChangeDetectionStrategy.OnPush occurs when an input property is changed or when an object reference is changed during an event on component etc.

就我而言,我是否必须手动调用 ChangeDetectorRef.detectChanges()来触发更改检测,还是我遗漏了什么?

In my case, do I have to manually call ChangeDetectorRef.detectChanges() to trigger change detection or am I missing something?

修改

只需清除一下,我正在使用 this.isLoading 通过相应地在HTML元素上添加/删除类来显示/隐藏加载状态.例如,

Just to clear, I' am using this.isLoading to show/hide loading state by adding/removing class on an HTML element accordingly. For example,

< div [class.processing] ="isLoading"></div>

推荐答案

将ChangeDetectionStrategy设置为OnPush时,仅当输入发生更改时,更改检测才会运行.由于您正在订阅一个可观察的并且正在更改的局部变量,因此不会将此更改通知给angular,因此您必须让自己知道.推荐的方法是使用ChangeDetectorRef.markForCheck(),它将在组件上方的树分支上执行更改检测

When setting ChangeDetectionStrategy to OnPush, change detection will run ONLY when an input has changed. Since you are subscribing to an observable and changing a local variable, angular will not be notified of this change so you have to let it know yourself. The recommended way is to use ChangeDetectorRef.markForCheck() which will perform change detection on the tree branch above your component

很棒的Thoughtram文章

还有一个出色的 Pascal Precht在这里演示

这篇关于HttpClient中的角度变化检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆