要解决这个问题,你可以使用 ngOnDestroy()
生命周期钩子,用它来取消参考 Angular 指令的订阅。
简单的方式是创建一个集中的订阅器,以确保 Angular 管理它们:
@Injectable({ providedIn: 'root' })
export class SubscriptionManagerService implements OnDestroy {
private subs: Subscription[] = [];
add(...subs: Subscription[]) {
this.subs.push(...subs);
}
ngOnDestroy() {
this.subs.forEach(sub => sub.unsubscribe());
}
}
在应用的根模块的 providers 数组中将它添加进去。现在,你的 Angular 指令可以注入 SubscriptionManagerService
,然后调用 add
方法来订阅所有的源。
export class MyDirective implements OnInit, OnDestroy {
private subs = new Subscription();
constructor(private subscriptionManager: SubscriptionManagerService) {}
ngOnInit() {
this.subs.add(
// your RxJS subscriptions here
);
}
ngOnDestroy() {
this.subs.unsubscribe();
}
}
最后,确保你只使用你的集中的订阅器来订阅与 Angular 指令相关的所有订阅。这样,当导航发生时,所有的订阅将被自动取消,而 Angular 指令也不会重复运行。