Dealing with Observables can lead to the variable returning as undefined

Could someone please clarify why the variable this.userDataObserver is undefined, causing the .next() function to fail? I'm quite puzzled by this.

I am in need of pushing some data into a service variable that can be accessed from other components (I am looking to avoid using local storage).

If anyone could shed some light on why this variable is undefined, despite being clearly set in the class, it would be greatly appreciated.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import 'rxjs/add/operator/map';


@Injectable()
export class globalService {
//Sets logon token
userData:any;
userDataRetrieval: Observable<any>;
userDataObserver: any;
//Sets + updates user info
userInfo: any;
userInfoRetrieval: Observable<any>;
userInfoObserver: any;

constructor() {
    this.userDataRetrieval = new Observable(observer => {
        this.userDataObserver = observer;
    })
    this.userInfoRetrieval = new Observable(observer => {
        this.userInfoObserver = observer;
    })

}
setUser(userData: any) {
    this.userData = userData;
    this.userDataObserver.next(this.userData); The issue arises as this.userDataObserver turns out to be undefined when calling this function from my component.
}

saveUserInfo(userInfo: any) {
    this.userInfo = userInfo;
    this.userInfoObserver.next(this.userInfo);
}

}

Answer №1

Instead of performing a direct call to

this.userDataObserver.next(this.userData)
, it seems like you could potentially benefit from trying the following approach:

updateUserInformation(userDataUpdate: any) {
    this.updatedUserData = userDataUpdate;
    this.userDataObserver = new Observable(observer => {
        observer.next()
    });
}

If this solution does not resolve your issue, please let me know...

Answer №2

If you take a closer look at the Observable source code, you will find the following information provided:

  /**
   * @constructor
   * @param {Function} subscribe - This function is invoked when an Observable is subscribed to. It receives a Subscriber as a parameter, allowing new values to be emitted with `next`, errors to be raised with `error`, and successful completions to be notified with `complete`.
   */
  constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
    if (subscribe) {
      this._subscribe = subscribe;
    }
  }

The code snippet above clearly demonstrates that the constructor of an Observable expects a callback function to handle subscriptions. If you did not invoke this `subscribe` function in your code, then the Observables you created were never actually subscribed to.

Given the limited context provided in your example, it is challenging to understand the specific goal you are aiming to achieve. Feel free to provide more details or explanations so that tailored guidance can be offered to help you reach your desired outcome.

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

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

Gaining insight from a separate module

Can events be passed to other components without requiring the component's selector? ...

What are some strategies for exporting methods without resorting to the use of import * as ...?

Imagine having a file structured like this: // HelperFunctions.ts export const dateFormat = 'MM/DD/YYYY'; export const isEmpty = (input: string | null | undefined): boolean => { if (input == null) { return true; } if (!in ...

Tips for fixing an issue in TypeScript while upgrading my Angular project from version 14 to version 16

Everything was running smoothly in my project until I decided to upgrade the Angular version from 14 to 16. Now, when I try to execute 'ng serve', an error is thrown and here it is: Error: src/app/paginas/descripcion/descripcion.component.ts:108 ...

Leveraging the power of Kendo UI for Angular, bind the click event of a kendoButton to a method associated with a variable within

I have a variable called "message" in my component that is of type "any" and contains a method named "actionnowrapper()". When I bind this method to a regular HTML button like so, everything works as expected. <button (click)="message.actionnowrapper( ...

Prevent Angular Router from Initiating NavigationStart

Can the NavigationStart event be prevented in Angular? I am attempting to display a customized confirmation modal when the user attempts to switch routes. constructor(private router: Router) { if(val instanceof NavigationStart){ //Display th ...

The proxy request gets delayed unless I utilize the http-proxy-middleware

Here is the code for a provider: @Injectable() export class GameServerProxyService { private httpProxy: httpProxy; constructor(@Inject(GameServerDetailsService) private gameServiceDetailsService: GameServerDetailsService) { this.httpP ...

Using RxJS to merge various HTTP requests into a unified and flattened observable array

Struggling with combining multiple http get requests simultaneously and returning them as a unified, observable array. In my current setup, the method returnNewCars() retrieves Observable<ICar[]> by executing a single http get request. However, in t ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

How can we assign various class names depending on the value of an object?

I have a set of objects stored in my component. I need to dynamically apply different classes based on the value of the ErrorLevel property within each object. If an object has ErrorLevel equal to 1, I want to assign the following classes to various elemen ...

What is the best way to remove query string parameters prior to running a function when a button is clicked?

I'm facing an issue trying to implement a button that filters events based on their tags. The problem arises when the tag value in the query string parameter does not clear when other buttons are clicked. Instead, the new filter tag value adds up with ...

Insert the object into a designated location within a multi-dimensional array

I've integrated a tree view into my Angular project and I'm looking to add an object to a specific position within an array. array const TREE_DATA: TreeNode[] = [{"name":"Demo","id":"demo_1","children ...

Two distinct approaches for user interface and application programming interface

Here's a non-technical question that's been on my mind lately. I've noticed that developers often create separate projects for their Angular applications using Visual Studio Code, and separate projects for their .NET Core Web API applicatio ...

Struggling to integrate WooCommerce Rest API with Angular 4

I'm facing a challenge while trying to integrate my WooCommerce REST API with Angular 4 in order to retrieve a product list for my Ionic 3 project. No matter what I try, the URL keeps throwing a 404 error and I can't seem to figure out where I&ap ...

Technique in CSS/SASS to repair a div

Seeking a solution for fixing divs with text in CSS. I am aware of the background-attachment: fixed; property which creates a fancy effect. Is there a similar property to "fix" divs with text or how can this be achieved in Typescript? Your insight would be ...

Angular Karma test - Error: Unable to access property 'recipientAddressId' of null

While attempting to test using karma, I encounter the following error... TypeError: Cannot read property 'recipientAddressId' of null Here is my Component: import { Component, OnInit } from '@angular/core'; import { Router } from &apos ...

Jest tests are failing to render React IonDateTime component

While executing Jest on an Ionic React component, I encountered a test failure consistently, regardless of whether the component had a time value or not. test('IonDateTime display', () => { render(<IonDatetime data-testid="foo" ...

Tips for maintaining the selected state of a row using Typescript and the option tag

Here is the code for a dropdown: <div class="col-md-6"> <label for="inertiaStart" style="float: left; width: 17%;">Inertia Start</label> <select ng-model="selectedShiftChannel" style="float: left; width: 70%;height: 26 ...

Generate an array that stores the values of objects passed from the parent component

Hi there, I am looking to create a single array in Angular that will store the values of objects coming from the parent component. Here are the objects sent from the parent component console.log('object',o): object {type: "TRA", designator: "EP ...