【发布时间】:2019-07-18 17:02:55
【问题描述】:
我在服务中遇到了 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
到目前为止,一切正常并且表现如我所料。第一次订阅被触发,然后componentA 的构造函数改变了globalVariable。
但是,当我导航到 componentB 并导航回 componentA 时,输出是:
=> hello
=> hello
=> hello
每次我导航回componentA 时都会添加一个。好像它创建了MyService 的新实例?还是离开时不销毁订阅?
信息:没有延迟加载。
【问题讨论】:
标签: angular service observable provider