简体   繁体   中英

ObjectUnsubscribedError after timeout

I am using an Event EventEmitter in a service component like this:

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 . 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"

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 .

Here is a proper solution to your problem using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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