我在离子项目中创建了一个提供程序,以从存储中检索用户对象,并在这里找到我的代码
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对象构造正确,我需要帮助。
答案 0 :(得分:0)
方法TypeError: must be real number, not str
返回一个promise,而您尝试立即访问它的值。
使用getStoredUser
方法解析promise后,您应该访问返回对象:
then
或者如果您与ES7兼容,则使用async\await:
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
}
});