简体   繁体   中英

Angular Lifecycle hook when there is a change on service

I have a service - let´s call ServiceA,

which makes multiple HTTP calls and I want to retrieve info when everything is calculated.For that I have a boolean variable - isEverythingProcessed, when that happens.

On my component - let´s call ComponentB,

I´m doing:

ngOnCheck(){
    
    if(this.serviceA.isEverythingProcessed){
    
    //dostuff
    
    }
}

this works, but it´s called hundred of times.There is any alternative for this, I mean to have a lifecycle that is implemented on component detecting when a variable of the service is being changed?

You could create an observable of the the soon-to-be-updated value onInit using rxjs, and subscribe to changes. This is how I've seen it done. Although, if something works and there's not a serious performance hit (an optimized fn call with a single if statement even if its called a few hundred times isn't really that bad although not ideal) I wouldn't overengineer it.

A Subject would probably suffice here, as your component is listening for the change. For example a BehaviorSubject would always emit when there is a listener, but you probably just want to listen when it emits, exactly when it emits. So create a Subject in the service instead of a boolean variable, subscribe to that in the component and do your magic when the subject emits. Remember to unsubscribe when component is destroyed!

So I suggest the following

Service:

isEverythingProcessed = new Subject<boolean>();

and when all your calculations are done, call next() on it:

this.isEverythingProcessed.next(true)

And component:

this.service.isEverythingProcessed.subscribe((bool: boolean) => {
  // do stuff!
})

STACKBLITZ DEMO

If you need an initial value and always trigger, I suggest a BehaviorSubject instead of Subject .

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