0

constructor当我在我的页面类中启动一个值时,我遇到了一个问题。我调用provider加载数据。内部service调用我可以看到数据被调用但是当我在服务调用之外调用我的变量时它说undefined。发生了什么?

主页.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);
          }

        });
      }
    });
  }
4

1 回答 1

2

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));
} 
于 2016-06-27T12:28:26.960 回答