angular - 超时后出现 ObjectUnsubscribedError

标签 angular

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

message: "object unsubscribed" name: "ObjectUnsubscribedError"

为什么会发生这种情况?

最佳答案

我不知道为什么会出现此错误,但这不是这里的主要问题。问题是您不应在服务中使用 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) 方法,每个订阅者都会收到更改通知。

关于angular - 超时后出现 ObjectUnsubscribedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47349444/

相关文章:

angular - RXJS 如何知道 Finalize 何时完成?

css - 使用 ngStyle 传递 CSS 值

javascript - 如何将输入字段类型 ="password"转换为 Angular 类型 ="text"?

javascript - 如何以编程方式更改 html select 标记中的选定选项

angular - 错误 TS1086 : An accessor cannot be declared in an ambient context in Angular 9

angular - 如何停止 mat-autocomplete 以将自定义用户输入值与给定选项分开?

Git 无法使用 IntelliJ 或 SourceTree 在我的项目上提交 Angular 文件夹

angular - 使用 Angular 的 ElementRef : "Property ' setFocus' does not exist on type 'ElementRef' . 设置 ionic 文本区域的焦点“

javascript - 如果满足条件则有 Angular 动画

c# - 从控制台运行 dotnet 核心应用程序时无法解决依赖关系