Why can't I save my get request in angular?

Hello I am starting in angular and I have no idea why this does not work any help.

It's simple, I make a get request and I try to save the data and I can't do it, I show you the code.

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ProfileComponent implements OnInit {
  userinfo;
  constructor(private readonly http: HttpClient) {
  }
  ngOnInit(): void {
    this.http.get<any>('/api/v0/user/userinfo?username=test').subscribe(data => {
      this.userinfo= data;
    });
    console.log("get: " + this.getuser);
  }
}

this is the json obtained in the request that I can see from the browser

{"id":2,"username":"test","email":"[email protected]"}

but what it shows by console is

get: undefined

HELP!

Upvotes: 0

Views: 68

Answers (2)

Nilo Alan
Nilo Alan

Reputation: 990

Here is a link on the stackblitz that I created to exemplify the asynchronous and synchronous:

https://stackblitz.com/edit/angular-ivy-teoitv?file=src/app/hello.component.ts

Basically Steve described the scenario for you ...

Basically the "delay" in the response from the endpoint returns you this undefined, but this can be treated with a loading while receiving the response from the server, here's an idea.

Another tip, you can use rxjs "tap" to console.log inside an observable.

https://www.learnrxjs.io/learn-rxjs/operators/utility/do

Upvotes: 0

Steve
Steve

Reputation: 1943

Firstly, as Luis mentioned in his comment, you need to access the correct variable in the console.log statement.

Second, your console.log is in the wrong place. It is firing before the API call is returning because of where you've placed it.

Try this:

ngOnInit(): void {
   this.http.get<any>('/api/v0/user/userinfo?
    username=test').subscribe(data => {
      this.userinfo= data;
      console.log("get: " + this.userinfo);
   });
 }

The reason being that the API call takes time to respond and the code has continued on with the next statement, the console.log, meaning this.userdata isn't set to anything because no data has come back from the server yet.

You will want to learn about asynchronous vs synchronous functions before you go must further. It is an important concept in web apps.

Upvotes: 1

Related Questions