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

Wow! Это было легко. Спасибо. – INgeek

Смежные вопросы