Does angular change detection happen in services?

Viewed 697

I'm just learning about Angular change detection. What I understood is that Angular runs change detection whenever some things happen inside a component. But what about in services?

Let's say that a service uses rxJs interval to do something (or nothing) every second. If I understood correctly that is an asynchronous operation. so does Angular run change detection and update the current views every second?

I've seen that some libraries are using ngZone (outside) for those kind of intervals, is that a mistake?

1 Answers

EDIT:

Actually, I have mistaken change detection event with re-rendering the component. I've made some deeper research and now I can say that change detection IS triggered from services, too. It is triggered across whole application when:

  1. some browser events appears (i.e. click, keyup)
  2. setInterval() or setTimeout() is executed
  3. There is a request executed with XMLHttpRequest

So, according to your concerns, creators of this library were aware that debounce usage in service will trigger change detection. It is not necessarily connected with updating templates, but it could trigger that.

Sorry for that mistake!

Original answer:

No, change detection does not happen in services as they don't have any template to re-render. If you want to update component according to changes in some service, you'll need to inject that service into component and share that data i.e. with BehaviorSubject.

If you'll push value to behavior subject you've subscribed to in component, that'll update that view, but when it's not subscribed - it won't rerender.

For your question with ngZone - it depends. According to Angular documentation you can use it to improve performance of your application, but only when it isn't connected to UI changes or error handling.

Related