首页 > 解决方案 > 当我在应用程序的不同页面之间移动时,为什么会触发根组件中订阅函数中的回调方法?

问题描述

我使用 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 属性更新时触发吗?我该如何解决这个问题?

标签: angulartypescriptrxjsobservable

解决方案


为了确保回调仅在组件中触发,您应该在组件被销毁时通过添加 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();
    });
  } 

推荐阅读