使用带有RxJS和Angular2的

时间:2016-02-23 14:05:15

标签: typescript angular observable rxjs

我仍在尝试自学Angular2(我真的需要找到更好的资源),但我有一个问题。我已将数据调用移至服务中,并且我正在使用Reactive Subject&在朋友的指示下行为主题。我的调用工作正常,我有一个来自真实后端的模拟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在准备好后收到返回的数据,显然没有更新...请告诉我我做错了什么我已经在这上面了几个小时!

1 个答案:

答案 0 :(得分:4)

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

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

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