Ionic 2 неопределенное значение после вызова поставщика услуг

Я столкнулся с проблемой, когда инициировал значение в классе моей страницы constructor. Я вызываю provider для загрузки данных. Внутри вызова service я вижу, что данные были вызваны, но когда я вызвал свои переменные вне вызова службы, он сказал undefined. Что случилось?

HomePage.ts

export class HomePage {
  public data: any;
  constructor(private nav: NavController, private auth: Auth, private params: NavParams) {
    this.auth.getProfile().then((profile) => {
      this.data = profile;
       console.log('here i can see data correctly ' + JSON.stringify(this.data));
    })
       console.log('here data undefined ' + JSON.stringify(this.data));
  } 

поставщик auth.ts

     getProfile(){
   return this.getToken().then((token) => {
   //   console.log(token);
      if (token) {
        return new Promise(resolve => {
          var headers = new Headers();
          headers.append('Content-Type', 'application/x-www-form-urlencoded');
          try {
            this.http.get('http://laraveldev/api/users/get_user?token=' + token).subscribe(data => {
              this.profile = data.json().data;
              //console.log('getProfile ' + JSON.stringify(this.profile));
              resolve(this.profile);
            });
          } catch (error) {
            console.log(error);
            this.data = { status: 'error' };
            resolve(this.data);
          }

        });
      }
    });
  }

person Bijak Antusias Sufi    schedule 27.06.2016    source источник
comment
Первый журнал консоли записывается внутри обратного вызова разрешения обещания, поэтому вы видите напечатанные данные, следующий - вне обратного вызова, поэтому к моменту выполнения этого оператора ваше обещание может быть не разрешено.   -  person wolverine    schedule 27.06.2016


Ответы (1)


Ваш service работает правильно. Чего вы не знаете, так это когда эта информация будет готова к использованию (и назначена вашему this.data свойству):

export class HomePage {
  public data: any;

  constructor(private nav: NavController, private auth: Auth, private params: NavParams) {
    this.auth.getProfile().then((profile) => {

      // Here you are inside the then(()=>{}) so your console log won't
      // be executed immediately. This console.log() will be executed 
      // after the promise gets resolved (it's async)
      this.data = profile;
      console.log('here i can see data correctly ' + JSON.stringify(this.data));
    })

    // This console.log() is outside the promise callback, so this line
    // will be executed immediately when you call the constructor,
    // without waiting for the service to send the response (and without 
    // that being stored in the this.data variable). This is Sync.
    console.log('here data undefined ' + JSON.stringify(this.data));
} 
person sebaferreras    schedule 27.06.2016
comment
это означает, как проверить данные с сервера и как этим управлять? - person Zaza; 24.08.2017