0
I am developing an application at angular 6 and am having a problem when I do Subscribe in the method that returns a single object in the HTTP request.
For example, making this request by my component:
ngOnInit() {
const empresaId = this.route.snapshot.params['empresaId']
this.empresaService.getEmpresa(empresaId).subscribe(resp => this.empresa = resp)
console.log(this.empresa)
}
My object company is undefined
, but if I put a log console inside the subscribe I’m returning my json normally
I noticed a detail. In case I create a type method:
obterEmpresa() {
const empresaId = this.route.snapshot.params['empresaId']
this.empresaService.getEmpresa(empresaId).subscribe(resp => this.empresa = resp)
console.log(this.empresa)
}
And I put this method in the button event, the first click returns undefined
. However, in the second click the object is normally filled with the answer.
This problem I am having only when the return is a single object. When it is an array, it works normally.
If you need my service method, there it is:
getEmpresa(id: number): Observable<Empresa> {
return this.http.get<Empresa>(`${URI}/empresa/${id}`)
}
this is not a problem but the expected behavior. http being asynchronous the object will only have value within Subscribe.
– Eduardo Vargas
Ola Eduardo, sorry is that I’m new in web development, and in case I leave the object in this case the this.empesa with value for all scope as it would be?
– paulo gama
The properties of a component have the scope of the component. The way you did this, company will get the value of http return when this request is successful.
– Eduardo Vargas
To see the value of your answer you can do so: this.empresaService.getEmpresa(empresaId). subscribe(Resp =>console.log(Resp))
– Eduardo Vargas