将存储数据映射到对象

时间:2016-12-15 16:20:57

标签: angular typescript ionic-framework ionic2

我正在尝试实现服务存储库。我知道我可以使用承诺,但我不知道如何实际实现它。这是我的代码:

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

使它运作的最佳做​​法是什么?

1 个答案:

答案 0 :(得分: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)
   });
}