Store the HttpRequest value within the component

I am encountering an issue with the Http Request value. I am sending an Http request to an Express API rest, and I want to display the value throughout my component. The data is available in the observable but not in other functions of my component. Can you explain why this is happening?


import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class UserModel {
  constructor (
    public id: string,
    public name: string,
    public type: string
  ) {}
}

@Injectable()
export class AskingService {

  BASE_URL = 'http://localhost:4201/';

  constructor(private http: HttpClient) { }

    // Get users from EXPRESS API REST
    getUserFromBdd() {
       return this.http.get<UserModel[]>(this.BASE_URL + 'api/fields');
      }
}

@Component({
  selector: 'app-asking-problem',
  template: `
`
})

export class AskingProblemComponent implements OnInit {

  constructor( private service: AskingService) { }

users;

ngOnInit() {
// subscribing to the service
this.service.getUserFromBdd().subscribe(data => {this.users = data, console.log('this.users =', this.users); });
// console return data

console.log('this.users =', this.users);
// console return undefined

}

}

Answer №1

This is a simple concept to understand. The reason why the action inside the subscribe function will execute much later than the outside call of "console.log('this.users =', this.users)" is because one is synchronous and the other is asynchronous.

After the http request resolves and emits a value that is received by the subscribed function, your user object will have the correct value. Do you follow?

You can learn more about Observables in Angular from the Angular Guide on Observables:

Observables

Passing messages between publishers and subscribers in your application is made easier with Observables. They offer numerous advantages over other event handling techniques, including support for asynchronous programming and handling multiple values.

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

Tips on delaying the return of the Angular compiler until the subscription is complete

I'm facing an issue with a function that needs to return a value while containing a subscription. The problem I'm encountering is that the return line is being executed before the subscription ends, testFunc(){ let objectType; let modul ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

Utilizing imported symbols across multiple script blocks in a Vue Single File Component

I am currently working with a Vue Single File Component that has two <script> blocks: one for setup and another for Vue Router's beforeRouteEnter handler, which cannot be used in setup. Both blocks may require some of the same imports. Interesti ...

What is the best way to prevent ticks from extending beyond the left side of the chart?

I am currently using Chart.js to create a multi-line chart. However, I am facing an issue where the first tick extends beyond the left side of the chart, causing the entire chart to shift over. I would like to find a solution where the first tick does not ...

What could be the reason for the webpack:// not showing up in Chrome after running ng build?

Greetings, I'm relatively new to Angular and have noticed a difference between using ng serve and ng build. When I use ng serve, I can see webpack:// in the Chrome debugger which allows me to navigate my TypeScript files for debugging. However, when I ...

Deliver a modification of the injected variable

I am facing an issue where I provide variables in a component and then try to inject/change them in the child component. Surprisingly, this setup works perfectly fine on the local server but once uploaded to the live server, the variable doesn't seem ...

Error in Typescript due to delegate function not being recognized post minification

Here is a code snippet that uses delegate: <pre> $.ajax(this.validateURL, { type: "post", url: this.validateURL, data: JSON.stringify(i), contentType: "application/json; charset=utf-8", dataType: "json", success: i => t.pro ...

Using TypeScript arrow function parentheses in the filter function

If I have an array of movie objects like this: const movies: Movie[] = [ movie1, movie2, movie3, movie4 ]; And if I want to remove a specific movie from the array, such as movie2, I can use the following code: movies = movies.filter( m => m !== ...

Tips for retrieving additional values from a chosen variable in Angular 10

Here is an array I have: export const Glcode = [ { id: 1, Type: 'Asset', Name: 'Cash at Head Office', code: '10018' }, { id: 2, Type: 'Asset', Name: 'POS ACCOUNT ', code: '10432' }, { ...

In React, how do public services compare to the Angular equivalent?

In order to maintain the state of a service between different views, I utilize Angular services that are declared as public. This allows me to store the necessary information within the service's variables. For example, in View 1, I am able to scan a ...

What could be causing the delay in loading http requests in Angular?

When attempting to update the array value, I am encountering an issue where it works inside the httpClient method but not outside of it. How can this be resolved in Angular 14? Here is a snippet from app.component.ts: ngOnInit(): void { this.httpC ...

Transmit location information in JSON format to server using Ionic3 and Angular4

I am new to the world of ionic framework and currently diving into ionic3-angular4. My app requires me to send the user's location details to the server once every 100 meters the user moves, in the form of a JSON string. After researching online examp ...

Issue: The <component> that you are looking for cannot be found in the '@chakra-ui/react' import/named module when using Next.js

I'm currently developing a Next.js application using Chakra-UI and TypeScript. The versions I am using include: "next": "13.1.1", @chakra-ui/icons": "^2.0.17", "@types/node": "18.15.11", "@t ...

Altering the dimensions of radio buttons

I am a newcomer to using material-ui. I am currently working on incorporating radio buttons in a component and would like to reduce its size. While inspecting it in Chrome, I was able to adjust the width of the svg icon (1em). However, I am unsure how to a ...

Ionic 3: Incorporating Baidu map functionality exclusively for web browsers

My current project with Ionic 3 involves incorporating the npm package angular2-baidu-map to display maps of China mainland. I have successfully obtained an API key for Baidu Maps (for the JS API), and the map functions perfectly in a browser (via ionic s ...

JSON.stringify omits any properties in a custom class that have not been explicitly declared in the constructor

I recently defined a new class in my code: export class SavedData{ public isDone : boolean; } After trying to stringify an instance of this class, I noticed that the isDone property was not included: console.log(new SavedData()); This resulted in a ...

Is there a way to receive autocomplete suggestions for sequelize classes that extend the Model class?

I have a specific Post class that I've created with various properties defined within it. However, I often find myself struggling to remember all the fields when actually typing them out, leading to errors in my code. @Table class Post extends Model { ...

Merging all Angular 2 project files into a single app.js document

I've scoured the depths of the internet for an answer to this burning question: How can I merge all my Angular 2 code, along with its dependencies, into a single file? Although this query has been posed countless times before, I bring a fresh perspect ...

Guide to accessing contact list on Ionic framework

I'm new to using Ionic and I'm trying to access the contact list in my app to display contacts only. Can someone please guide me on how to achieve this? I watched a tutorial on YouTube but the code provided doesn't seem to work. I've ad ...

Is there a specific Angular signature pad that is capable of saving signatures as images?

I'm looking to create a signature pad for saving user signatures on my enterprise website. Can anyone recommend the best package for this task? ...