2017-05-26 91 views
0

我有一个奇怪的问题: 我有一个简单的函数来得到我的myData.ts数据库的用户信息。db.get方法不起作用,打字稿

test = <any>{}; 

    getUserInfoFromPouch(filter: string):any{ 

    this.db.get(filter).then((result) => { 
     this.test = result; 
    }) 
    return this.test; 
    } 

它有效...有点儿。

我调用该函数在我的用户数据页面的构造函数:

this.userData = this.myData.getUserInfoFromPouch(this.userId); 
console.log('------------------t1----------------------------------'); 
console.log(this.userData); 
console.log('------------------t2----------------------------------'); 
console.log(this.myData.test); 

,但我只得到一个ampty对象返回:如果我通过一个按钮再次调用该函数

------------------t1---------------------------------- main.js:62736:9 
Object { } main.js:62737:9 
------------------t2---------------------------------- main.js:62738:9 
Object { } 

,我得到了我期望的实际输出。 如果我不先调用构造函数中的功能,我必须使用按钮两次,以获得数据。 这很混乱。 我尝试了许多不同功能的拼法,如:

test = <any>{}; 

     getUserInfoFromPouch(filter: string):any{ 

     return this.db.get(filter).then((result) => { 
     }) 
     } 

test = <any>{}; 

     getUserInfoFromPouch(filter: string):any{ 

     this.db.get(filter).then((result) => { 
     return result; 
     }) 
     } 

我在做什么错? 谢谢你的帮助。

Btw。我在数据库中只有一条记录。 (用于测试目的)

编辑: 好吧,我想这样的功能:

async getUserInfoFromPouch(_id: string){ 


    try { 
     this.test = await this.db.get(_id); 
    } catch (err) { 
     console.log(err); 
    } 
    console.log('------------------t3----------------------------------'); 
    console.log(this.test); 

    } 

,我调用该函数在我的用户页面的构造函数,像以前一样。 之后我打电话的功能,我填写我的用户数据与功能测试VAR:

this.myData.getUserInfoFromPouch("userinfo"); 
    this.userData = this.myData.test; 
    console.log('------------------t1----------------------------------'); 
    console.log(this.userData); 

但用户数据是空的。而我得到的功能console.output后,我做的事:

this.userData = this.myData.test; 

我做得非常不对;-(

+0

的可能的复制[如何返回从一个异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Saravana

+0

MHM我试着一个异步的aproach,但它仍然无法正常工作。如果我调用函数,我得到预期的数据,但由于某些原因,我得到的数据(如果我把它叫做顺序): this.myData.getUserInfoFromPouch(this.userId); this.userData = this.myData.test; 的console.log('------------------ T1 ----------------------- -----------'); console.log(this.userData);在console.log(this.userData)后面加上 ; – user3793935

回答

1

好吧,这与承诺解决的问题

this.myData.getDocumentById('userInfo').then(res=>{ 
     if (res!=undefined){ 
     this.userData=res; 
     } 
    }).catch(err=>{ 
     console.log('userInfo-error: ', err) 
    }); 

现在的作品,因为它应该 我getDocumentById功能锁这样的:

getDocumentById(id: string):any { 
    this.syncTwoWay(); 
    return this.db.get(id).then((doc) => { 
     return doc; 
    }).catch((err) => { 
     console.log('getDocumentById' + err); 
    }); 
    }