Exception: ObjectUnsubscribedError when working wi

2019-02-25 15:47发布

问题:

I am still trying to teach myself Angular2 (and I really need to find some better resources) but I have a question. I have moved my data calls to a service and I am using Reactive Subject & BehaviorSubject after instruction from a friend. My calls works, I have a mock REST service from a real back end that gives me a data object (that is an oject of mock user data), my response matches a type I have defined however in my top level app (called App.ts) I have to wait for the response. Now this is where I am doing something wrong as when I try to obtain or work with the data I get [Exception: ObjectUnsubscribedError] when I console.log.

Here's the problem, here is my top level app

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
    }
}

Here is my 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();
        });
    }

The results from the console.log(this.userDataService.loginInUser.last()); in the App.ts gives me the following:

_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!!!!

I just want my App.ts to receive the returned data once it is ready, it obviously isn't updating... please tell me what I am doing wrong I have waisted hours on this!

回答1:

I would subscribe to the loginInUser observable to be notified when the current user is updated:

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

Don't forget that an HTTP request is asynchronous so you can receive data after the constructor of your App component is executed.