0

I am new in ionic and angular. I want to get data from API but I can't access the data.

Here is my code

  public items: any;

  constructor(
    public navCtrl: NavController, 
    public modalCtrl: ModalController, 
    public navParams: NavParams, 
    public http: Http) {

    let headersToken = new Headers();
    headersToken.append('Authorization', 'Bearer token here');

    this.http.get('http://localhost:8000/api/data',{headers : headersToken}).map(res => res.json()).subscribe(data => {
            this.items = data;
        });

  }       

  ionViewDidLoad(){ 
    console.log(this.items);
  }

And the result of IonViewDidLoad is undefined.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
reeouw
  • 35
  • 6

3 Answers3

0

It might be that your HTTP call Isnt finished when IonViewDiDLoad is called. Try setting a timeout and see if it works. Otherwise, it might be that your HTTP request is not returning the proper data

user7722867
  • 478
  • 3
  • 17
  • but if I put console.log(items) after this.items = data, the data in shown perfectly – reeouw Aug 31 '17 at 08:52
  • Yes, that it is because you will only enter that part of your code if the data is emitted from your subscription. This works if you want to print your data as soon as you get it. – user7722867 Aug 31 '17 at 20:02
0

You can do it like this:

Note: Due to the async nature you need to do it as shown below.

 ionViewDidLoad(){ 
    let headersToken = new Headers();
    headersToken.append('Authorization', 'Bearer token here');

    this.http.get('http://localhost:8000/api/data',{headers : headersToken}).map(res => res.json()).subscribe(data => {
            this.items = data;
            console.log(this.items);
        });

  }
Sampath
  • 63,341
  • 64
  • 307
  • 441
0

You need to understand why this is happening.

Http.get is an asynchronous call.

The way you have written your code is your console.log(this.items); is execcuted before you have received output from http call or before the call is completed.

To make sure you get data after call, you need to put console inside subscribe.

I have added below console.log(this.items) inside subscribe

        this.http.get('http://localhost:8000/api/data',{headers : headersToken})
.map(res => res.json())
.subscribe(data => this.items = data, // 1st param where you get data
           (error) => console.log(error), // error if any
           () =>  conosle.log("call is finished"+this.items) // call is completed. here you call ionViewDidLoad() as well.
           );

      }       

      ionViewDidLoad(){ 
        console.log(this.items);
      }

I hope this helps.

Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80