繁体   English   中英

超时后出现ObjectUnsubscribedError

[英]ObjectUnsubscribedError after timeout

我在这样的服务组件中使用事件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 这很好用,但是当会话超时并且路由器默认返回登录页面时,就会出现问题。 再次登录后出现此错误

消息:“对象取消订阅”名称:“ ObjectUnsubscribedError”

为什么会这样呢?

我不知道为什么会收到此错误,但这不是这里的主要问题。 问题是您不应该在服务中使用EventEmitter,因为它不能保证保持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)方法,并且将向每个订户通知更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM