Observable.of(array) updates every time setInterval is fired

 ̄綄美尐妖づ 提交于 2019-12-08 10:04:54

问题


I’m having some weird behaviour when using Observable.of(array) and angular’s async pipe. Maybe I’m using it wrong but I can’t understand it.

I have a view.html and view.ts file in Ionic 3 (angular 4). I’m doing a Observable.of(items). Items is just an array with objects. And in my view I have: let item of items | async. It all works great but when I also do a setInterval in the view.ts every 1000 miliseconds... the view updates every 1000 miliseconds. Even when the setInterval doesn’t do anything!

Am I using it wrong? I can’t understand the behaviour..!


回答1:


Use OnPush strategy. With this strategy only impacted items are evaluated, that is, components where events fired or otherwise were marked for check. Also, items are compared in shallow mode, that means only references are checked. This requires you to not mutate objects.

Import ChangeDetectionStrategy from @angular/core, then add changeDetection: ChangeDetectionStrategy.OnPush to the @Component decorator.

For instance, instead of this.array.push(value) use this.array = this.array.concat(value).

When the value is updated asynchronously, like in an http call or timer, add ChangeDetectorRef and call markForCheck() on the callback.




回答2:


The setInterval method is "patched" in such a way, that it triggers a change detection cycle.

Take a look here for more info.

Some relevant sections of the link:

Basically application state change can be caused by three things:

Events - click, submit, …

XHR - Fetching data from a remote server

Timers - setTimeout(), setInterval()

They are all asynchronous. Which brings us to the conclusion that, basically whenever some asynchronous operation has been performed, our application state might have changed. This is when someone needs to tell Angular to update the view.

Who notifies Angular?

Alright, we now know what causes application state change. But what is it that tells Angular, that at this particular moment, the view has to be updated? Angular allows us to use native APIs directly. There are no interceptor methods we have to call so Angular gets notified to update the DOM. Is that pure magic? If you’ve followed our latest articles, you know that Zones take care of this. In fact, Angular comes with its own zone called NgZone, which we’ve written about in our article Zones in Angular. You might want to read that, too. The short version is, that somewhere in Angular’s source code, there’s this thing called ApplicationRef, which listens to NgZones onTurnDone event. Whenever this event is fired, it executes a tick() function which essentially performs change detection.



来源:https://stackoverflow.com/questions/47463569/observable-ofarray-updates-every-time-setinterval-is-fired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!