【发布时间】:2020-02-24 14:35:52
【问题描述】:
我正在尝试通过使用 observables 和 Subject 来建立组件之间的通信。
这是我的服务。
公共服务
private style = new Subject<string>();
getStyle(): Observable<any> {
return this.style.asObservable();
}
updateStyleArray(styleToApply) {
this.style.next(styleToApply);
}
我尝试使用 getStyle() 方法订阅的组件,在构造函数中有以下代码。
底栏
this.commonService.getStyle().subscribe(style => {
console.log('I am firing in order not to be fired!!!');
});
我调用next()方法的组件有如下代码。
侧边栏
this.commonService.updateStyleArray('This is the name of a style');
我已将代码简化到最低限度,但它仍然不会触发 subcribe() 函数。
---->Stackblitz
解决方案和注意事项
上述技术的作用就像一个魅力,以便在组件之间建立通信。错误是因为
app-bottom-bar 是用ngIf* 实现的,并且没有调用构造函数*,因此没有调用订阅函数。
*<app-bottom-bar *ngIf="isBottomBarVisible"></app-bottom-bar> 。
【问题讨论】:
-
您如何注册您的服务?作为组件提供者、模块提供者或
@Injectable({ providedIn: 'root' })? -
@KurtHamilton ---> @Injectable({ providedIn: 'root' })
-
你能在 stackblitz 中重新创建吗?
-
添加了 StackBlitz
-
bottom-bar应该在哪里呈现?我没在里面看到它
标签: angular observable subject