angular - 当我在应用程序的不同页面之间移动时,为什么会触发根组件中订阅函数中的回调方法?
问题描述
我使用 Angular 10 并创建了这个服务器,它返回一个 observable:
export class CountrySelectionService {
private _activeCountry = new BehaviorSubject(this.getCountries()[0]);
public getActiveCountryPush(): Observable<CountrySpec> {
return this._activeCountry.asObservable();
}
constructor(private utilService:UtilService){}
getCountries(): CountrySpec[] {
return [new CountrySpec("assets/images/canadaFlag.svg", Country.CA, "sales@dwinfo.com"),
new CountrySpec("assets/images/usaFlag.svg", Country.US, "sales@dwinfo.com")]
}
setActiveCountry(countrySpec: CountrySpec): void {
this._activeCountry.next(countrySpec);
}
}
在 ngOnInit 函数的 app.component.ts(root component) 文件中,我使用上述方法:
ngOnInit(): void {
this.countrySelectionService.getActiveCountryPush().subscribe({
x=> { someFoo(x.name) }
});
}
我希望只有在 _activeCountry 属性更新时才会触发 someFoo 回调方法。但实际上, someFoo 回调方法不仅会在 _activeCountry 属性更新时触发,而且会在我移动到应用程序的另一个页面时触发。
知道为什么 someFoo 方法不仅在 _activeCountry 属性更新时触发吗?我该如何解决这个问题?
解决方案
为了确保回调仅在组件中触发,您应该在组件被销毁时通过添加 ngOnDestroy 事件取消订阅。
subscriptions: Subscription[];
ngOnInit(): void {
let sub = this.countrySelectionService.getActiveCountryPush().subscribe({
x=> { someFoo(x.name) }
});
this.subscriptions.push(sub);
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
推荐阅读
- javascript - 正则表达式检查不同的顺序?
- javascript - 使背景适合页面网格,没有滚动条
- python - 创建python包后无法调用函数
- reactjs - 在 Vercel 上获取本地和生产
- json - 如何从 VS CODE 中的 json 文件中选择所有值?
- python - 获取父类
- sql - 如何从 React + Express 服务器中的数据库中查询“附加 10 个”结果
- sql - 用于填充缺失值的 SQL 连接
- amazon-web-services - 无法再使用 AWS Toolkit for VS 2019 进行部署
- terraform - 错误:无效索引空元组给定键未标识此集合值中的元素