Issue: Encountering an ObjectUnsubscribedError while using Observables in RxJS and Angular2

Currently, I am in the process of self-teaching Angular2 and realize that I need to find better resources. One issue I am facing is related to moving my data calls to a service and utilizing Reactive Subject & BehaviorSubject as recommended by a friend. While my calls are functioning properly with a mock REST service producing a data object (containing mock user data) that matches the defined type, I encounter an error when attempting to work with this data in my top-level app called App.ts. Specifically, upon trying to access or manipulate the data, I receive an [Exception: ObjectUnsubscribedError] message in the console.

Let me outline the problem starting with 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
    }
}

Next, let's examine 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 log from

console.log(this.userDataService.loginInUser.last());
displays:

_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 simply want my App.ts to receive the data once it becomes available, but it appears that the data is not updating. Can someone please assist me in identifying what I may be doing incorrectly? I have already spent hours on this!

Answer №1

To stay up-to-date with the current user, I would opt to subscribe to the loginInUser observable:

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

Keep in mind that HTTP requests are asynchronous, so data may be received after the constructor of your App component has already been called.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming Angular 2 quickstart application for deployment on Google Cloud infrastructure

Attempting to deploy a basic project on Google Cloud platform has proven to be more challenging than expected. The simple quickstart project can be accessed here, and functions flawlessly locally. While there are other providers like Heroku that offer one ...

The use of the `/deep/` combinator in CSS has been phased out and is set to be completely removed

After updating my angular to version 4.0.0 and chrome to 62.0.3202.94, I encountered the following error message: [Deprecation] /deep/ combinator in CSS is deprecated and will be removed in M63, around December 2017. Refer to for more information. The ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

What is the best way to associate a select dropdown with a form in Angular 2 using formBuilder

After conducting some research, I was surprised to find that the process is not as straightforward as I had expected. I have come across various methods using ngModel, such as Bind and fetch dropdown list value in typescript and Angular2, among others. Ho ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

Pattern matching for validating multiple email addresses

I need assistance with validating multiple email inputs using regex in Angular. I am looking to enforce a specific format for the emails, such as: Examples: *****@zigurat.com *****@test.com *****@partlastic.com The ***** can be any characters, but the ...

The functionality of Angular JSON browserTarget has been deprecated and is no longer supported

I encountered a warning where 'borwserTarget' was deprecated in my Angular JSON file. Instead of using 'browserTarget', it prompted me to use 'builtarget'. However, it states that the data path must have a required property &a ...

The primary filter for ag-Grid in Angular 2+

When using the default filtering on ag-grid, I find that the timing between typing and filtering is too quick. Is there a method to slow down this process? Perhaps instead of triggering the filter when typing stops, it could be activated by pressing a bu ...

The ng test option is failing to execute effectively

Attempting to conduct unit tests utilizing Karma and Jasmine through the ng test is proving to be a bit challenging. Upon issuing the following command: ng test --watch=false --code-coverage --main ./src/main/resources/public/scripts/xyz/workspace/commons ...

Using the `disableSince` option in `mydatepicker` for validating date of birth

Currently, I am utilizing the mydatepicker plugin for my calendar field, specifically for the Date of Birth field. It is important for me to disable future dates by setting the current date as a reference point. While exploring the documentation, I came ...

Transferring information between AngularJS and Angular applications

Having two applications on localhost: http://localhost/testsite (Angular js app) http://localhost:4200 (Angular app) Seeking assistance in sharing data from Angular JS to Angular application. Any guidance would be appreciated. Thank you. ...

Is React 18 compatible with both react-redux and react-router?

At present, my react application is running on the following versions: react 17.0.x react-dom 17.0.x react-redux 7.2.x react-router-dom 5.x.x react-scripts 4.0.x redux 4.x.x My initial step towards upgrading to react@18 involved updating react-scripts to ...

Issue with asynchronous function: "Cannot assign type 'Promise<MyType[]>[]' to type 'MyType[]'"

After converting this function to async, I've been encountering issues with type annotations being out of sync: export default async function formatCallRecordsForPGPromise( rawCalldata: CallRecord[], ): Promise<SaveableCallRecord[]> { const ...

The absence of defined exports in TypeScript has presented a challenge, despite attempting various improvement methods

I've exhausted all available resources on the web regarding the TypeScript export issues, but none seem to resolve the problem. Watching a tutorial on YouTube, the presenter faced no such obstacles as I am encountering now. After updating the tsconf ...

Typescript constructor that accepts an object as an argument instead of traditional parameters

My constructor is becoming lengthy and not structured the way I would prefer. I am looking to pass an object to my constructor so that I can access fields by their names. Here is how the class looks currently. export class Group { id: string; constru ...

What to do when your Angular app isn't bootstrapping properly and you need to add a

I have a query regarding my Angular application. It retrieves its initial configuration data from an API and can initialize the app using that configuration. Below is the ApiConfigService: export class ApiConfigService { public initialized: Promise< ...

Trigger event when ngModel changes

Currently, I am trying to perform a test on a select element... <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple> <option [value]="route ...

The angular component cannot be bound as it is not recognized as a valid property

In an attempt to conditionally assign a class based on the value of a boolean variable, I have declared the variable in the parent component: public alteredSidebar: boolean; This is my approach for dynamically setting the classname: <div [class ...

Validate multiple email addresses in a single input field, such as adding multiple recipients to the CC field in an email form using

Currently using Angular2 and primeng to create a basic email form with the following input fields: To: Cc: Message: Here is an excerpt of the code from my component class: constructor(private fb: FormBuilder) { this.createForm(); } createForm ...

What causes Next.js to struggle with recognizing TypeScript code in .tsx and .ts files?

Webpages lacking a declared interface load correctly https://i.stack.imgur.com/DJZhy.png https://i.stack.imgur.com/r1XhE.png https://i.stack.imgur.com/zXLqz.png https://i.stack.imgur.com/Z1P3o.png ...