首页 > 解决方案 > 即使在组件销毁后订阅服务 observable 也会发出

问题描述

我在服务中遇到了可观察的问题。以下代码说明了这一点:

@Injectable({
  providedIn: 'root'
})
export class MyService {
  public globalVariable: BehaviorSubject<string> = new BehaviorSubject('');
}

我有一个功能组件:

export class ComponentA implements OnInit {
   constructor(public myService : MyService ) {
      this.myService.globalVariable.next('newValue');
   }

   ngOnInit() {
      this.myService.globalVariable.subscribe(_ => console.log('=> hello'));
   }
}

应用模块:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ComponentAModule,
    ComponentBModule,
    AppRoutingModule
  ],
  providers: [MyService],
  bootstrap: [AppComponent]
})
export class AppModule {
}

最后是项目结构:

app-module.ts
app-routing.module.ts
-components
-- componentA
--- componentA.module.ts
--- componentA-routing.module.ts
--- componentA.component.ts
--- componentA.component.html
-- componentB
--- componentB.module.ts
--- componentB-routing.module.ts
--- componentB.component.ts
--- componentB.component.html

现在我面临的问题是,当我导航到 时componentA,输出是:

=> hello
=> hello

到目前为止,一切都很正常,并且表现如我所料。第一个订阅被触发,然后globalVariablecomponentA的构造函数改变。

但是,当我导航到componentB并导航回 时componentA,输出为:

=> hello
=> hello
=> hello

每次我导航回componentA. 好像它创建了一个新实例MyService?还是离开时不销毁订阅?

信息:没有延迟加载。

标签: angularserviceobservableprovider

解决方案


你需要在unsubscribe里面ngOnDestroy

import { Subscription } from 'rxjs';

globalVariable$: Subscription;

ngOnInit() {
  this.globalVariable$ = this.myService.globalVariable.subscribe(_ => console.log('=> hello'));
}

ngOnDestroy() {
  this.globalVariable$.unsubscribe();
}

推荐阅读