无法从提供者 - 离子2获得价值 [英] Unable to get value from provider - ionic 2

查看:89
本文介绍了无法从提供者 - 离子2获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含构造函数代码的提供程序:

I have created a provider with constructor code:

constructor(private storage: Storage) {

    this.datas = null;
    this.getUserinfoDB()
        .then(
        data => {
            this.uid = data['id'];
            console.log("UID FROM PROVIDER "+this.uid);
        }
    );
}

我刚将其导入另一个ts文件:
like:

and I just imported it into another ts file: like:

constructor(public crudStorageProvider: CrudStorageProvider) {                
  console.log("UID: " + crudStorageProvider.uid);
}

此导入和所有内容一切正常:

everything is fine with this import and all:

但是 console.log(UID:+ crudStorageProvider.uid); 这里我得到了未定义。

but console.log("UID: " + crudStorageProvider.uid); here i am getting undefined.

,我的控制台订单是:

UID: undefined
UID FROM PROVIDER: 6  

谢谢,

推荐答案

从输出序列,很明显数据是在 console.log(UID:+ crudStorageProvider.uid)之后设置的;

From the output sequence, it is clear that the data is set after console.log("UID: " + crudStorageProvider.uid);.

这是承诺异步性质的正常结果。

This is a normal consequence of the asynchronous nature of promises.

你应该有你的 CrudStorageProvider 中的一个函数是这样的:

You should have a function in your CrudStorageProvider instead like so:

getUID(){
  if(this.uid){
     return Promise.resolve(this.uid);
  }else{
     return this.getUserinfoDB()
        .then(
        data => {
            this.uid = data['id'];
            console.log("UID FROM PROVIDER "+this.uid);
            return this.uid;
        }
    );
  }
}

然后致电

this.crudStorageProvider.getUID().then((uid)=>  {console.log("UID: ",uid);} )

这篇关于无法从提供者 - 离子2获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆