I have a problem with Http Request value. I do an Http request to an Express API rest and I would like to see the value all over the component. I can have the data on the observable but not in other function of my component. Could you explain me why?
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
}
}
This is simple. The action called inside the subscribe will execute much after the outside call "console.log('this.users =', this.users)" because one is sync and the other is async.
Your object user will have the correct value but just after the http resolve and emit a value that will be received by the subscribed function. Got it?
From the Angular Guide on Observables :
Observables
Observables provide support for passing messages between publishers and subscribers in your application. Observables offer significant benefits over other techniques for event handling, asynchronous programming , and handling multiple values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.