2016-06-27 1 views
0

私のページの値をconstructorで開始したときに問題が発生しました。私はproviderを呼び出してデータを読み込みます。内部にserviceコールがありますが、データが呼び出されているのがわかりましたが、サービス外で変数を呼び出すとundefinedと表示されました。何が起こった?サービスプロバイダに電話をかけた後に2の定義されていない値

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)); 
    } 

あなたが正常に動作しているservice

 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); 
      } 

     }); 
     } 
    }); 
    } 
+0

最初のコンソールログあなたがいる理由である約束の解決のコールバックの内側に書かれている:あなたが知っているしていない何を、その情報を使用する準備ができて(そしてあなたへthis.dataプロパティを割り当てられている)であるがですデータが表示されているのを見ると、次のコールバックの外側にあるので、そのステートメントが実行されるまでに約束が解決されていない可能性があります。 – wolverine

答えて

2

auth.tsプロバイダ。

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)); 
} 
+0

サーバーからのデータを検証する方法とこれを管理する方法を意味しますか? – Zaza

関連する問題