调用服务提供者后,Ionic 2未定义的值

时间:2016-06-27 08:50:40

标签: angular typescript ionic2 ionic3

我在页面provider课程中启动了一个问题时遇到了问题。我调用service来加载数据。在undefined调用内部我可以看到数据被调用但是当我在服务之外调用我的变量时调用它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)); } 。发生了什么事?

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

        });
      }
    });
  }

auth.ts提供商

 m = 0

 def f(x):
     print(m)
     return x

1 个答案:

答案 0 :(得分: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));
}