简体   繁体   中英

Angular Change Detection in HttpClient

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

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.

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

Edit

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>

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

在此处输入图片说明

There is more is more info on this in this great thoughtram article

And an excellent presentation here by Pascal Precht

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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