Angular Promises – Async and Await
In December of 2016 Async and Await were introduced in Typescript or in Angular v2.1. This allowed developers to write asynchronous functions to work with Promises. The following is an example of a promise using async and await.
Optional – If you don’t have a service created.
To create a new service in your angular application please run the following in your command line;
ng generate service services/financial-stock
We will use HttpClient and toPromise().
No open the new financial-stock-service.ts file under the services folder.
Add the following code.
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; import { SharedService } from './shared.service'; @Injectable({ providedIn: 'root' }) export class StockFmpService { constructor(private http: HttpClient) { } async getCurrentPrice(ticker: string): Promise<any> { const URL = `https://financialmodelingprep.com/api/v3/stock/real-time-price/${ticker}`; return await this.http.get(URL).toPromise(); } }
Now that we have an asynchronous service method to get the stock price we can call it from a component.
In your component.ts file.
async getStockPrice(id: number) { await this.stockService.getCurrentPrice('GOOG') .then((res) => { console.log('Answer Data: ', res); this.stockPriceData = res.data; }, ).catch((error) => { console.log(error); }); }
This is just a basic example of a Promise using Async and Await.