2016-12-15 292 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