简体   繁体   中英

How to destroy services that are programmatically injected into dynamically created angular components?

In Angular, it is possible to load and view components dynamically at runtime by calling viewContainerRef.createComponent(factory) on an instance of ViewContainerRef , passing a factory that can create an instance of the component.

By passing an Injector instance as third argument, it is possible to provide additional services (programmatically) to the dynamically loaded component (and its sub-components), eg:

const injector = Injector.create({
    providers: [
        { provide: AdditionalService, useClass: AdditionalService },
    ],
    parent: parentInjector
});

const componentRef = viewContainerRef.createComponent(factory, undefined, injector);

However, the additional service is only instantiated, if the dynamically created component needs it - so we don't know, if the injector holds an instance of this service yet. Some time later, we destroy the dynamically created component:

// some time later, we destroy the dynamically created component:
componentRef.destroy();

Unfortunately, destroying the component does not destroy the (possibly existing) service automatically, Also the injector does not provide a method for destruction. so it is not possible to destroy the additional service.

How can we maintain the lifecycle (especially ngOnDestroy() ) of those programmatically provided services correctly?

Note: I've implemented a short example on StackBlitz that demonstrates this behavior. It loads a component dynamically that requires two services. The first service is provided on component level ( @Component({ provides: [ FirstService ]} ), the second via injector as described above. When the component is destroyed, the first service is destroyed correctly while the second "stays alive".

Also the injector does not provide a method for destruction, so it is not possible to destroy the additional service.

There is injector.destroy which actually calls SecondService.ngOnDestroy . If you think about it - it seems logical but I failed to find any docs for this method at all...

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