在Angular中,当Custom Elements从DOM中被移除时,可以使用ngOnDestroy
生命周期钩子来自动销毁服务。以下是一个示例:
首先,创建一个Angular服务,命名为MyService
,并在其中添加一些逻辑:
import { Injectable, OnDestroy } from '@angular/core';
@Injectable()
export class MyService implements OnDestroy {
constructor() { }
// 添加一些逻辑
doSomething() {
console.log('Doing something...');
}
// 在销毁时执行的逻辑
ngOnDestroy() {
console.log('Service destroyed!');
}
}
接下来,在Angular组件中使用该服务,并在组件销毁时取消订阅:
import { Component, OnDestroy } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template: 'My Component
',
providers: [MyService]
})
export class MyComponent implements OnDestroy {
constructor(private myService: MyService) { }
ngOnDestroy() {
console.log('Component destroyed!');
}
}
最后,在自定义元素中使用该组件,并在元素被移除时销毁:
class MyElement extends HTMLElement {
connectedCallback() {
const component = document.createElement('app-my-component');
this.appendChild(component);
}
disconnectedCallback() {
this.removeChild(this.firstChild);
}
}
customElements.define('my-element', MyElement);
上述代码中,当my-element
被添加到DOM时,会创建一个app-my-component
组件,并将其添加到my-element
内部。当my-element
被从DOM中移除时,会触发disconnectedCallback
方法,该方法会移除app-my-component
组件,从而触发组件的销毁逻辑,同时也会触发服务的ngOnDestroy
方法。
通过这种方式,可以确保在Custom Elements从DOM中移除时,服务会自动销毁。