我在服务组件中使用Event EventEmitter,如下所示:
export class SettingsService {
public sidebarColor = '#D80B0B';
public sidebarColorUpdate: EventEmitter<string> = new >EventEmitter();
然后我从其他组件订阅它:
this.settingsService.sidebarColorUpdate.subscribe((color: string) => {
if (color === '#fff') {
this.normalFontColor = 'rgba(0,0,0,.6)';
this.dividerBgColor = 'rgba(0,0,0,.1)';
} else {
this.normalFontColor = 'rgba(255,255,255,.8)';
this.dividerBgColor = 'rgba(255, 255, 255, 0.5)';
}
});
然后取消订阅ngOnDestroy
。这很好用,但是当会话超时并且路由器默认返回登录页面时,问题就出现了。再次登录后,我收到此错误
消息:“object unsubscribed”名称:“ObjectUnsubscribedError”
为什么会这样?
答案 0 :(得分:1)
我不知道你为什么会得到这个错误,但这不是主要问题。问题是不应该在服务中使用EventEmitter ,因为it does not guarantee to remain Observable。
以下是使用Observables解决问题的正确方法:
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
export class SettingsService {
// Source variable should be private to prevent subscribing to it
private sidebarColorUpdatedSource = new Subject<string>();
// Expose an observable to allow subscribers listen to the updates
sidebarColorUpdated$ = this.sidebarColorUpdatedSource.asObservable();
// Expose a public method for updating the sidebar color
updateSidebarColor(color: string): void {
// Update the color
// Notify subscribers
this.sidebarColorUpdatedSource.next(color);
}
}
组件:
private sidebarColorUpdated$: Subscription;
ngOnInit(): void {
this.sidebarColorUpdated$ = this.settingsService.sidebarColorUpdated$.subscribe(color => {
// Do whatever you need
});
}
ngOnDestroy(): void {
if (this.sidebarColorUpdated$)
this.sidebarColorUpdated$.unsubscribe();
}
当您需要更新侧边栏颜色调用SettingsService.updateSidebarColor(color: string)
方法时,每个订阅者都会收到更改通知。