简体   繁体   English

超时后出现ObjectUnsubscribedError

[英]ObjectUnsubscribedError after timeout

I am using an Event EventEmitter in a service component like this: 我在这样的服务组件中使用事件EventEmitter:

export class SettingsService {
    public sidebarColor = '#D80B0B';
    public sidebarColorUpdate: EventEmitter<string> = new >EventEmitter();

I then subscribe to it from other components like this : 然后,我从其他组件订阅它,如下所示:

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)';
    }
 });

And then unsubscribe in the ngOnDestroy . 然后退订ngOnDestroy This works great but the problem now arises when the session times out and the router defaults back to the login page. 这很好用,但是当会话超时并且路由器默认返回登录页面时,就会出现问题。 After login in again I get this error 再次登录后出现此错误

message: "object unsubscribed" name: "ObjectUnsubscribedError" 消息:“对象取消订阅”名称:“ ObjectUnsubscribedError”

Why is this happening ? 为什么会这样呢?

I can't tell why do you get this error but that's not the major problem here. 我不知道为什么会收到此错误,但这不是这里的主要问题。 The issue is that you should not be using EventEmitter in the services because it does not guarantee to remain Observable . 问题是您不应该在服务中使用EventEmitter,因为它不能保证保持Observable

Here is a proper solution to your problem using Observables: 这是使用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);
    }
}

Component: 零件:

private sidebarColorUpdated$: Subscription;

ngOnInit(): void {
    this.sidebarColorUpdated$ = this.settingsService.sidebarColorUpdated$.subscribe(color => {
        // Do whatever you need
    });
}

ngOnDestroy(): void {
    if (this.sidebarColorUpdated$)
        this.sidebarColorUpdated$.unsubscribe();
}

When you need to update the sidebar color call SettingsService.updateSidebarColor(color: string) method and each subscriber will be notified of the change. 当您需要更新侧边栏颜色时,请调用SettingsService.updateSidebarColor(color: string)方法,并且将向每个订户通知更改。

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

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