Accessing information independent of Observable data in TypeScript

When attempting to send an HttpRequest in Typescript, I encountered an issue where the received data could not be stored outside of the subscribe function. Despite successfully saving the data within the subscribe block and being able to access it there, when trying to print the 'user' variable outside of the subscribe function, it appears as undefined. How can I retrieve the data from the subscription to use it outside of this scope?

private user: User;

public sendHttpLogin(username: string, password: string) {

  this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
    //save the data on a User Object
    this.user = data;
    //this works fine
    console.log(this.user)
  });

  //this is undefined
  console.log(this.user);
}

Answer №1

The console.log statement is being executed before the response from http.get is received, resulting in an undefined value.

Your initial console.log output is accurate; data can only be utilized once it has been returned from the get function.

To maintain the application's flow, consider invoking another function at that point.

private user: User;

public sendHttpLogin(username: string, password: string) {

  this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
    this.continueApp(data)
  })
}

private continueApp(data){
    this.user = data
}

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

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

Navigating with fun! 2 in scala following a submission using angularJs

Up to this point, I've been using the traditional method of submitting a form and redirecting to the desired page like so: The HTML section : <form name="createArtistForm" method="post" action="/admin/createArtist"> Artist Name : <input ...

TypeScript: "The type is generic and can only be accessed for reading." - Error code 2862

Consider this sample JS function that requires type annotations: const remap = (obj) => { const mapped = {}; Object.keys(obj).forEach((key) => { mapped[key] = !!key; }); return mapped; }; I am attempting to add types using generics (in ...

How can I pass a parameter to my MEAN application using a clean and readable URL

Seeking suggestions for passing a parameter into a MEAN application without compromising the URL aesthetics. I must find a solution that does not involve client-side storage. The following Express route effectively integrates the parameter into the Angular ...

How can I store various data types in a single array in TypeScript?

I have a scenario I need help with. Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs? interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cat ...

Unleashing the power of await with fetch in post/get requests

My current code has a functionality that works, but I'm not satisfied with using it. await new Promise(resolve => setTimeout(resolve, 10000)); I want to modify my code so that the second call waits for the result of the first call. If I remove the ...

Error encountered while testing karma: subscription function is not recognized

I encountered an issue with my karma unit test failing with the following error message. "this.gridApi.getScaleWidth().subscribe is not a function" GridApi.ts export class GridApi { private scaleWidthSubject = new BehaviorSubject<{value: number}& ...

What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

The supabase signup function keeps showing me the message "Anonymous sign-ins are disabled." Can anyone help me understand why this is happening?

I'm currently in the process of setting up authentication in Next.js with supabase, but encountering an issue when attempting to execute the signUp function. The error message I'm seeing is: Anonymous sign-ins are disabled Below is the snippet o ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Explaining the process of defining an object type in TypeScript and the conversion from JavaScript

Currently, I am attempting to enhance the background of a React website developed in typescript (.tsx) by incorporating particles. My approach involves utilizing the particle-bg component available at: https://github.com/lindelof/particles-bg However, whe ...

The $http Service encounters a failure with an unknown status code

Difficulty Integrating AngularJS, jQuery, and Adobe Panel Creation I recently updated the versions of AngularJS and jQuery for my project. Previously, I was using jquery-1.11.0.min.js and AngularJS 1.2.10. Now, I want to utilize the latest available versi ...

Verify Ionic storage for an item

Is there a way to display an introductory slider only once for new users when they install the app? Solution If the user installs the app, set an item in the storage called intro with a value of false When the user opens the app, check the intro item. I ...

Highcharts memory leakage issue arises when working with jQuery version 2.X

After extensive testing on my AngularJS application, I have discovered a memory leak when using Highcharts with the latest version of jQuery (2.1.4). Below are links to two plunkers for comparison: Using jQuery 1.8.2: http://plnkr.co/edit/lQ6n5Eo2wHqt35OV ...

What is the best choice for storing data in my Angular2+ component: an object or an observable?

If I were to create an angular2+ component that fetches data from an API and displays its name, which approach would be considered more idiomatic? Initial Strategy: Using thing as an object In this scenario, the component subscribes to a websocket observ ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Choose a specific location on a vehicle illustration within a pop-up window. The image should be partitioned into 6 separate sections

I have a project for my client where they need to choose a car and then indicate where the damage is located on an image, which is divided into 6 sections. I'm struggling to figure out how to achieve this. I initially thought z-index would work, but ...

Encountering a problem with the 'string' parameter when using TypeScript

I keep encountering the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ barkingRoadProject: string[]; }'. No index signature with a paramet ...

Using an aria-label attribute on an <option> tag within a dropdown menu may result in a DAP violation

Currently, I am conducting accessibility testing for an Angular project at my workplace. Our team relies on the JAWS screen reader and a helpful plugin that detects UI issues and highlights them as violations. Unfortunately, I've come across an issue ...

Implementing an Express server within Angular application directories

I recently encountered a problem while trying to integrate Express into my Angular app for server communication. After searching online for solutions, I came across a guide that helped me get started. However, there are still some aspects that remain uncle ...