Ionic 2:: Unusual TypeError 从 JSON in angular 中检索 属性

Ionic 2:: Unusual TypeError retrieving a property from JSON in angular

我在我的离子项目中创建了一个提供程序来从存储中检索用户对象,这是我的代码

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class ApiProvider {

  public user: any;

  constructor(
    public storage: Storage
  ) {}

  getStoredUser(){
    this.storage.get('user').then(
      data => {
        this.user = data;
        console.log(data);
      }
    );    
    return this.user;
  }

当我从 getStoredUser() 函数控制台记录用户对象时, 这就是我得到的

{
   authcode: "USR_65267H4390"
   church_id: 2
   email: "test@gmail.com"
   fullname: ""An**a A***e""
   id: 55
   phone: "08*****7"
   skills: "Football, chess, scrabble"
}

json 数据记录正确,但是当我尝试在不同的组件上执行此操作时

export class HomePage {

    obj: any;

    userObj:any = {
      name:'',
      email:'', 
      phone:'',
      skills:'',
      unit:'',
      church_id:2 //hardcoded on every request...
    };


  constructor(
    public navCtrl: NavController,
    public api: ApiProvider,
    public storage: Storage
  ) {} 

 ngOnInit():void{     

    this.obj = this.api.getStoredUser();

    //console.log(this.obj) - outputs the object above, no errors..
    //if(this.obj.length < 1)  - gives me error too.. i've tried everything 

    if(this.obj !== null){  //------------ this line gives me error.
        this.userObj = {
          name: this.obj.fullname, // ------- this property gives me error.
          email: this.obj.email, 
          phone: this.obj.phone,
          skills: this.obj.skills,
          unit:'', 
          church_id: this.obj.church_id 
        }
    } else{
      // do something else.
    }

  }

这是我在尝试读取全名时遇到的错误...

 " Uncaught(in promise): TypeError: Cannot read property 
 'fullname' of undefined TypeError: at Homepage.webpack.jsonp

这是我在尝试读取 this.obj

的长度时遇到的错误
  " Uncaught(in promise): TypeError: Cannot read property 
  'length' of undefined TypeError: at Homepage.webpack.jsonp...

我已经尝试了所有方法,但我不知道该怎么做。json 对象构建正确,我需要帮助。

方法 getStoredUser return 是 promise 并且您正在尝试立即访问它的值。

您应该在使用 then 方法解析 promise 之后访问 return 对象:

this.api.getStoredUser().then(obj => {
      this.userObj = {
          name: obj.fullname, // ------- this property gives me error.
          email: obj.email, 
          phone: obj.phone,
          skills: obj.skills,
          unit:'', 
          church_id: obj.church_id 
        }
});

如果你兼容 ES7,则使用 async\await

this.obj = await this.api.getStoredUser();

//if(this.obj.length < 1)  - gives me error too.. i've tried everything 

if(this.obj !== null){  //------------ this line gives me error.
    this.userObj = {
      name: this.obj.fullname, // ------- this property gives me error.
      email: this.obj.email, 
      phone: this.obj.phone,
      skills: this.obj.skills,
      unit:'', 
      church_id: this.obj.church_id 
    }
}