首页 文章

Ionic 2 :: Unusual TypeError以角度从JSON中检索属性

提问于
浏览
-2

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

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对象构造得当,我需要帮助 .

1 回答

  • 0

    方法 getStoredUser 返回promise,您正试图立即访问它的值 .

    使用 then 方法解析promise后,应该访问返回对象:

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

相关问题