Variable me returning Undefined which is assigned inside subscribe

Asked

Viewed 817 times

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 ?

  • 1

    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.

  • 2

    I think you’re confused. The method subscribe is part of the class Observable working with asynchronous calls. I believe you were getting undefined because I was calling the console.log before the value is returned by subscribe. What I can recommend is that you read this material and try to understand how asynchronous calls work with the Observables.

  • 1

    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 variable data. It’s not because you’re undefined at the time of console.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.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.