2016-12-15 370 views
1

我正在嘗試實現服務存儲庫。我知道我可以使用承諾,但我不知道如何實際執行它。這裏是我的代碼:將存儲數據映射到對象

export class Account { 
    constructor(
     public id: String, 
     public name: String, 
     ) 
     { } 
} 
@Injectable() 
export class AccountService { 
    constructor(private storage:Storage){} 

    getAccount(id:any): Account {  
     var account : Account; 
     this.storage.get("my-db").then((data) => { 
      if(data && data[id]){ 
       account = new Account(data[id].id,data[id].name); 
     } 
      else 
       account = new Account("",""); 
     }); 
     return account; 
    } 
} 

,當我使用它:

... 
constructor(public accountService:AccountService) { 
    console.log(accountService.getAccount(1111)); 
} 
... 

返回undefined

使其工作的最佳實踐是什麼?

回答

2

您應該等到承諾完成並從getAccount方法返回承諾。

getAccount(id: any): Account { 
    var account: Account; 
    //return from 
    return this.storage.get("my-db").then((data) => { 
    if (data && data[id]) { 
     account = new Account(data[id].id, data[id].name); 
    } else 
     account = new Account("", ""); 
    return account; 
    }); 
}; 

組件

constructor(public accountService:AccountService) {| 
    //though it could be better if you can shift this to ngOnInit hook 
    accountService.getAccount(1111).then((account)=>{ 
     console.log(account) 
    }); 
} 
+0

哇!那很簡單。謝謝。 – INgeek