【问题标题】:Exception: ObjectUnsubscribedError when working with Observables with RxJS and Angular2异常:使用 RxJS 和 Angular2 处理 Observables 时出现 ObjectUnsubscribedError
【发布时间】:2016-06-05 09:58:04
【问题描述】:

我仍在尝试自学 Angular2(我真的需要找到一些更好的资源),但我有一个问题。我已将我的数据调用移至服务,并且在朋友的指导下我正在使用 Reactive Subject 和 BehaviorSubject。我的调用有效,我有一个来自真实后端的模拟 REST 服务,它为我提供了一个数据对象(即模拟用户数据的对象),我的响应与我在顶级应用程序(称为 App. ts) 我必须等待回复。现在这是我做错的地方,因为当我尝试获取或使用[Exception: ObjectUnsubscribedError] 时得到的数据时,console.log

问题出在这里,这是我的顶级应用

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {Observable, Subject, BehaviorSubject} from 'rxjs';
import {UserContact, UserStatus} from './types/types';

// more stuff, then...

import {UserDataService} from './services/user-data/UserDataService';

@Component({
    selector: 'app',
    providers: [...FORM_PROVIDERS, UserDataService],
    directives: [...ROUTER_DIRECTIVES, FooterNavigation, TopNavigation, ContactsList],
    pipes: [],
    template: require('./app.html')
})

export class App {

    constructor(public userDataService: UserDataService) {
        console.log(this.userDataService.loginInUser.last());
    }

    ngOnInit() {
        // even if I try to output here I get the same problem
    }
}

这是我的用户数据服务

import {Injectable} from 'angular2/core';
import {UserStatus} from '../../types/types';
import {Subject, BehaviorSubject, Observable} from 'rxjs';
import {Http, Headers, Response} from 'angular2/http';

@Injectable()
export class UserDataService {

    public loginInUser: Subject<UserStatus> = new BehaviorSubject<UserStatus>(null);
    public currentUser: UserStatus;

    constructor(public http:Http) {
        this.loadUserStatus(); // Here I define the false user to use in my App
    }

    private loadUserStatus():void {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.http.get('/restservice/userstatus', {headers: headers}).subscribe((response:Response) => {
            var userStatus: UserStatus = new UserStatus(response.json());
            this.currentUser = userStatus;
            this.loginInUser.next(this.currentUser);
        }, (error:Response) => this.handleError, () => {
            this.loginInUser.complete();
        });
    }

App.ts 中 console.log(this.userDataService.loginInUser.last()); 的结果给了我以下信息:

_isScalar: false
completeSignal: false
destination: BehaviorSubject
dispatching: false
errorSignal: false
isUnsubscribed: false
observers: Array[0]
operator: LastOperator
source: BehaviorSubject
_hasError: false
_isScalar: false
_subscriptions: undefined
_value: UserStatus // the data does seem to be here!!!!
completeSignal: true
dispatching: false
errorSignal: false
isUnsubscribed: true
observers: undefined
value: [Exception: ObjectUnsubscribedError] // Here is the problem!!!!

我只想让我的 App.ts 在准备好后接收返回的数据,它显然没有更新...请告诉我我做错了什么我已经浪费了好几个小时了!

【问题讨论】:

    标签: typescript angular observable rxjs


    【解决方案1】:

    我会订阅loginInUser observable,以便在当前用户更新时收到通知:

    constructor(public userDataService: UserDataService) {
      this.userDataService.loginInUser.subscribe(
        (currentUser) => {
          console.log(currentUser);
        }
      });
    }
    

    不要忘记 HTTP 请求是异步的,因此您可以在 App 组件的构造函数执行后接收数据。

    【讨论】:

    • 这更有意义,谢谢!我没有意识到我可以订阅他的 App.ts 并认为我必须使用 .next() 或 .last() 来监听更改
    • 不客气!事实上,next 在观察者级别触发事件,last 运算符允许在您使用 debounceTime 缓冲事件时获取最后一个事件。要获得通知,您需要订阅 observable...也许您可以看看这个关于 Rx 的精彩教程:gist.github.com/staltz/868e7e9bc2a7b8c1f754
    • 我还有一个关于将界面上的 currentUser 渲染到 DOM 中的快速问题...我应该再写一个问题吗?
    • 是的,也许会更好 ;-) 在 cmets 中回答并不是很方便,尤其是如果我们想放一些代码 sn-ps... 但这取决于问题 ;-) 让我们试试这里...
    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多