Angular 6 methods that handle Observable data from HTTP GET requests complete execution before constructing the final Data

My goal is to retrieve data from a REST endpoint and then construct a List of instances to return. However, I'm facing an issue where the HTTP GET function returns an Observable method that always results in an empty list before populating it with data from the response.

Below is the code snippet:


 public getUsers() {
    let responseValue = this.http.get(this.utils.provideserviceURL('http://test.com/users'));

    responseValue.toPromise()
    .then(result => {
      let usersList: User[] = [];
      let jsonResult = result.json();
      for (let temp of jsonResult) {
        let tempUser = new User(jsonResult.id, jsonResult.username, jsonResult.password, jsonResult.firstName, jsonResult.lastName);
        usersList.push(tempUser);
      }
      console.log(usersList);
      return usersList;
    })
    .catch(err => {
      // Error while fetching Users
      console.log('Error');
    });

  }

The problem lies in the fact that the function initially returns undefined before displaying the console log with the correct data.

I am uncertain about the proper usage of the toPromise() method. If there's already a discussion on this topic, please guide me towards it or mark this question as a duplicate.

Answer №1

One reason for this behavior in JavaScript is that it does not wait for the response to come back before executing further code. It may seem illogical to return something based on a response that has not yet been received.

My suggestion would be to store your list in an attribute and then use it in your component or wherever you need to access it.

public users: Users = undefined

public getUsers() {
    let responseValue = this.http.get(this.utils.provideserviceURL('http://test.com/users'));

    responseValue.toPromise()
    .then(result => {
      let usersList: User[] = [];
      let jsonResult = result.json();
      for (let temp of jsonResult) {
        let tempUser = new User(jsonResult.id, jsonResult.username, jsonResult.password, jsonResult.firstName, jsonResult.lastName);
        usersList.push(tempUser);
      }
      console.log(usersList);
      this.users = usersList;
    })
    .catch(err => {
      // Error while fetching Users
      console.log('Error');
    });

  }

Answer №2

This is my approach (I noticed that toPromise has been deprecated),

constructor(private dataService: DataService){}

myEmailAddress: string = '';
myIdentifier: number = 0;

ngOnInit(){
this.dataService.fetchUser()
.subscribe((information: WhoAmI) => {
  this.myEmailAddress = information.Contacts.find(x=>x.ContactTypeName == "Email").ContactValue;
  this.myIdentifier = information.ID;
});

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

Using Angular and Typescript to implement mathematical formulas involving date object subtraction

I need help converting the following Excel formula to Typescript. I keep running into an error that says 'The left-hand and right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type'. Can anyon ...

Utilizing Services in Angular 2

I am new to learning angular2 and encountering an issue with calling a service. The service call is successful, but I am unsure how to handle the data. In Angular1, we would handle it like this: DemoService.getExchangeDataConnection().then(function(respon ...

Asyncronous calls in Angular involve executing tasks without

The issue seems to be related to the timing of updates for the controlSelected and isAssessmentDataLoading variables. The updateQuestions() method is invoked within the ngOnInit() method, which is triggered when the component is initialized. However, the ...

"Troubleshooting Angular 2 Directives That Cause Errors

Hey there, I'm currently working on understanding ANGULAR 2 routing, but I've encountered an error that's causing some trouble. Here's the issue I'm facing: app/app.component.ts(7,12): error TS2345: Argument of type '{ s ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

Discovering an element in an Array using Angular 2 and TypeScript

In my setup, I have a Component and a Service: Component: export class WebUserProfileViewComponent { persons: Person []; personId: number; constructor( params: RouteParams, private personService: PersonService) { ...

Crafting a versatile type guard in TypeScript - step by step guide!

Issue with Generic Type Guard I'm facing a problem while trying to create a generic type guard for various Token types. The current implementation I have is as follows: export function isToken<T extends Token>(token: any): token is T { for (c ...

Issues with displaying results from a local JSON file using Angular 4 services seem to be

I have developed a User.service.ts service where I have implemented the following code: getContactDetials(){ return this.http.get(this.config.apiUrl + 'assets/data/contact-details.json') .map(response => response.json()); ...

What is the best way to retrieve data in Server Components?

In my current process of handling fetch, I am following the guidelines outlined in the document below: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch async functi ...

"Encountering a Challenge with NgFor when Displaying Data within an Expand

Trying to utilize Tailwind's Accordion feature to display an array of posts has revealed a peculiar issue. While the console log confirms the presence of the post array, expanding the accordion seems problematic. Curiously enough, this problem only ar ...

Step-by-step guide on generating a deb or exe file for an Angular Electron application

I am currently developing an Angular 6 project and I have a desire to turn it into a desktop application using Electron. After successfully installing Electron in my project, I encountered some challenges when trying to create builds for multiple platforms ...

Tips for fetching individual item information from Firebase real-time database using Angular 9 and displaying it in an HTML format

product.component.ts import { AngularFireDatabase } from '@angular/fire/database'; import { ProductService } from './../product.service'; import { ActivatedRoute } from '@angular/router'; import { Component, OnInit} from &apo ...

Restrict input to only alphabets in HTML using Angular

Can someone guide me on how to restrict input to only accept alphabet characters in Angular? I am working with reactive forms and currently using a pattern validation which only gets triggered when the form is submitted. However, I need the input field t ...

The design system package may experience difficulty loading material styles correctly

Our company is currently in the process of developing a design system that can be easily integrated into multiple projects as a package. While building the package has been successful, we encounter an error after installing it and trying to import the them ...

Utilizing Eithers to effectively manage errors as they propagate through the call chain

I'm delving into functional programming and exploring different ways to handle errors beyond the traditional try/catch method. One concept that has caught my attention is the Either monad in various programming languages. I've been experimenting ...

Help! My Angular CLI version 8.2.2 is displaying squares instead of the Font-awesome icons

I successfully added Font Awesome using the command npm install --save font-awesome angular-font-awesome from https://www.npmjs.com/package/angular-font-awesome. After linking it in my angular.json file: "styles": [ "src/styles.css", "node_modu ...

What could be causing my D3.js stacked bar chart to show inaccurate results?

I'm encountering some challenges while creating a stacked bar chart in d3.js. The current appearance of my chart is depicted here (developed with D3.js): https://i.sstatic.net/G6UA6.png However, I aim to achieve a design similar to this one (crafted ...

Encountering an error in Cytoscape using Angular and Typescript: TS2305 - Module lacks default export

I am working on an Angular app and trying to integrate Cytoscape. I have installed Cystoscape and Types/cytoscape using npm, but I encountered an error when trying to import it into my project. To troubleshoot, I started a new test project before implement ...

Retrieving attributes from a reactive object in TypeScript

I have a question regarding accessing values in Typescript. Whenever I load my website, I make a call to a service that fetches user data. private currentUserSource = new ReplaySubject<IUser>(1); currentUser$ = this.currentUserSource.asObservable ...

Transform the string property extracted from the API into a JSON object

When making a request to an API, the data returned to the front end is in the following format: { name: 'Fred', data: [{'name': '"10\\" x 45\\" Nice Shirts (2-pack)"', 'price' ...