1

i am very very new in ionic and angular , i follow all the step that ionic provide at the blog to config api http://blog.ionic.io/10-minutes-with-ionic-2-calling-an-api/

after follow all the step when i try to console the result which is store in the variable that return undefined here is the code of provider:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiServiceProvider {
   link = 'https://randomuser.me/api/';
   data :any;
   constructor(public http: Http) {
     console.log('Hello ApiServiceProvider Provider');

     this.load();
    }
load() {
    if (this.data) {
        return Promise.resolve(this.data);
    }
    return new Promise(resolve => {
        this.http.get(this.link)
            .map(res => res.json())
            .subscribe(data => {
                this.data = data.results;
                resolve(this.data);
            });
    });
  }
}

here is the code for page/home.ts

 import { Component } from '@angular/core';
 import { NavController ,ActionSheetController , AlertController } from 'ionic-angular';
 import { ResultPage } from '../result/result';
 import { ApiServiceProvider } from '../../providers/api-service/api-service';

 @Component({
   selector: 'page-home',
   templateUrl: 'home.html',
   providers: [ApiServiceProvider]
 })
  export class HomePage {
   users: any;
    constructor(public navCtrl: NavController, public alertCtrl:AlertController, public actionCtrl:ActionSheetController,public apiProvider:ApiServiceProvider) {
    this.getUsers();
   }
   getUsers() {
     this.apiProvider.load()
     .then(data => {
       this.users = data;
    });
   console.log(this.users);
 }

any help is appreciated. thanku

1 Answer 1

1

The code inside load() is asynchronous, meaning it will take some time to complete. While that code is working, the next statement will to executed. In your case, the next statement is console.log(this.users).

This leads to console.log(this.users) being executed before load() is completed, and this.users will therefor be undefined.

Solve this by moving the console.log inside the then callback like this:

getUsers() {
  this.apiProvider.load()
    .then(data => {
      this.users = data;
      console.log(this.users);
    });
}

I recommend you to read up on how PROMISES in javascript works :)

Sign up to request clarification or add additional context in comments.

1 Comment

you are great thankx a lot , i spend 3 days on this and you just see that code and correct in just 1 attempt.. thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.