3
In the code below, the variable date is returning me Undefined, now if I put console.log(this.data); inside subscribe returns me with the correct value.
import { Component, OnInit } from '@angular/core'; import {Http} from '@angular/http'; @Component({ selector: 'app-aniversario', templateUrl: './aniversario.component.html', styleUrls: ['./aniversario.component.css'] }) export class AniversarioComponent implements OnInit { data: any; constructor(private http: Http) { } ngOnInit() { this.http.get('assets/aniversarios.json').subscribe(res => { this.data = res.json(); }); console.log(this.data); } }
How can I take the value of res who is in the subscribe ?
maybe this problem is related to the object that this is referencing in each function and not to the callbacks, as the duplicate suggests. if it is that: before ngOnInit() puts var self = this; and works within the subscribe with self instead of this.
– guijob
I think you’re confused. The method
subscribe
is part of the classObservable
working with asynchronous calls. I believe you were gettingundefined
because I was calling theconsole.log
before the value is returned bysubscribe
. What I can recommend is that you read this material and try to understand how asynchronous calls work with theObservables
.– Carlinhos
Exactly what @Carlinhos said,
subscribe
works with asynchronous calls, in which case the console is logging in even before the response is returned and played to the variabledata
. It’s not because you’reundefined
at the time ofconsole.log
that the data is not there, but that at that time it was not available. If you implement an interface you will see what date you receive the values after loading.– Tiago Boeing