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
}
}