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;
我做得非常不對;-(
的可能的複製[如何返回從一個異步調用的響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Saravana
MHM我試着一個異步的aproach,但它仍然無法正常工作。如果我調用函數,我得到預期的數據,但由於某些原因,我得到的數據(如果我把它叫做順序): this.myData.getUserInfoFromPouch(this.userId); this.userData = this.myData.test; 的console.log('------------------ T1 ----------------------- -----------'); console.log(this.userData);在console.log(this.userData)後面加上 ; – user3793935