How to return value of promise using angular 2
Promises provide us with abstractions that help us deal with the asynchronous nature of our applications. Since we don't know how much time will those operations take (and therefore, when is the data going to be available) you need to use the then()
method to execute some code when the data is ready to be used:
this.getCustomer()
.then((data) => {
// Here you can use the data because it's ready
// this.myVariable = data;
})
.catch((ex) => {
console.log(ex);
});
first, you need func to get all your data:
getAll(): Promise<Phrase[]> {
return phrasesPromise;
}
second, if you need one item you can use
ngOnInit() {
this.phraseService
.getAll()
.then((result: Phrase[]) => this.phrases = result);
}
This is a Promise
, so you need to use then
:
getCustomer()
.then(customer => {
customer.name;
customer.email;
});
If you are using TypeScript, or a version of JavaScript that supports async
/await
, you can do this:
var customer = await getCustomer();
customer.name;
customer.email;
The above will need to be in an async
function, like so:
async displayCustomerDetails() {
var customer = await getCustomer();
customer.name;
customer.email;
}