简体   繁体   中英

Angular Service - subscribe to component OnDestroy

I have a service ( MyService ) that is injected in my MyComponent . I want MyComponent to call a function on MyService , and pass some sort of a reference to this particular instance of MyComponent so that the service knows when the instance has been destroyed .

What is the proper object to pass to MyService from MyComponent so that MyService can know when the component is destroyed? I am assuming there is a some sort of an observable MyService can subscribe to in order to get this information.

EDIT: Some more context

MyService is in charge of creating @angular/cdk Portal and has two functions:

attachComponent<T>(component: ComponentType<T>, data?: ComponentData<any>)

and

attachTemplate<T>(templateRef: TemplateRef<T>, viewContainerRef: ViewContainerRef) .

This service emits an observable that MyHeaderComponent subscribes to, in order to reflect some content that MyComponent has asked for it to render. However, for clean-up reasons and so that every single other component doesn't have to import this service and clear the clontents of the header, I want to know when the caller of that function has been destroyed, and do it in the service so I only have to code it there. Basically, the idea is, when the caller to either attachTemplate or attachComponent is destroyed, then the contents should be automatically cleared. I'm trying to centralize this logic in MyService so that not every single component that injects MyService and uses this functionality has to implement some sort of a clearContent() function in ngOnDestroy.

Try to use subjects. You can create a subject in MyComponent and let MyService subscribe to that subject. You can call subject.complete() inside of your ngOnDestoy lifecycle hook of MyComponent. Then MyService will get to know the state of MyComponent. For reference about subjects: https://ncjamieson.com/understanding-subjects/

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