异常:使用 RxJS 和 Angular2 的 Observables 时出现 ObjectUnsubscribedError

Exception: ObjectUnsubscribedError when working with Observables with RxJS and Angular2

我仍在尝试自学 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
    }
}

这是我的 UserDataService

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 在准备好后接收返回的数据,它显然没有更新...请告诉我我做错了什么我已经浪费了几个小时!

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

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

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