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

関連する問題