我正在尝试通过使用可观察对象和Subject建立组件之间的通信。
这是我的服务。
CommonService
private style = new Subject<string>();
getStyle(): Observable<any> {
return this.style.asObservable();
}
updateStyleArray(styleToApply) {
this.style.next(styleToApply);
}
我尝试使用getStyle()方法订阅的组件,在构造函数内部具有以下代码。
BottomBar
this.commonService.getStyle().subscribe(style => {
console.log('I am firing in order not to be fired!!!');
});
我在其中调用next()方法的组件具有以下代码。
Sidebar
this.commonService.updateStyleArray('This is the name of a style');
我已将代码简化到最低限度,但仍然无法启动subcribe()函数。
----> Stackblitz
解决方案和注释
上述技术的作用很吸引人,目的是在组件之间建立通信。该错误是由于引起的app-bottom-bar是用ngIf*
实现的,未调用*构造函数,因此未调用subscription函数。
* <app-bottom-bar *ngIf="isBottomBarVisible"></app-bottom-bar>
。
BottomBarComponent
构造函数未调用。因此,您实际上尚未订阅。
修复-将此粘贴在app.component.html
<app-bottom-bar></app-bottom-bar>
您可以更改
private style = new BehaviorSubject <string>();
可能会在侧边栏之前渲染底栏,从而导致订阅丢失。 BehaviorSubject将使所有组件都可以使用最后一个订阅。
谢谢
Subject
将不会为新订户重播旧值。因此,如果您在进行订阅之前调用了updateStyleArray()
,则只有在对updateStyleArray()
进行新的调用时,它才会触发。
为解决这个问题,您可以将Subject
替换为ReplaySubject并将缓冲区大小设置为1:
private style = new ReplaySubject<string>(1);
现在,可观察到的样式将缓冲最后一个值,并且如果您在调用
style.next()
之后进行订阅,则还会发出此值。