angular - 即使在组件销毁后订阅服务 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
到目前为止,一切都很正常,并且表现如我所料。第一个订阅被触发,然后globalVariable
由componentA
的构造函数改变。
但是,当我导航到componentB
并导航回 时componentA
,输出为:
=> hello
=> hello
=> hello
每次我导航回componentA
. 好像它创建了一个新实例MyService
?还是离开时不销毁订阅?
信息:没有延迟加载。
解决方案
你需要在unsubscribe
里面ngOnDestroy
:
import { Subscription } from 'rxjs';
globalVariable$: Subscription;
ngOnInit() {
this.globalVariable$ = this.myService.globalVariable.subscribe(_ => console.log('=> hello'));
}
ngOnDestroy() {
this.globalVariable$.unsubscribe();
}
推荐阅读
- java - 如何阻止 gradle 在 java 8 上应用 javafxplugin?
- excel - 宏在 VBE 中正确运行,而不是从 Excel 文件中的加载项按钮
- javascript - 查询使用SQL变量时的Mysqli PHP准备语句
- c - 是否有任何编译器和库 strcmp() 返回 -1 0 和 1 以外的值?
- java - 如何模拟兔子消息到 Spring StreamListener?
- c++ - 解释算术表达式 C++
- sql - 将表与 SQL Server 2012 中的 sql/tsql 进行比较
- google-chrome-devtools - 在查询选择器中传递多个属性
- docker - 如何将字体添加到 Windows Docker 容器/图像?
- sql - ADF,从自动创建的文件夹中提取文件