How to use Angular Promise using Typescript await and async (ES6)

Krishna KV
 
Team Leader, Aspire Systems
October 24, 2016
 
Rate this article
 
Views
10784

The typescript async and await is a ES6 functionality. It used to allow the developers to write the asynchronous code to flows as a synchronous method, without write a handler or a callback function. The similar pattern was used in C# to make use of the promises.

AppService.ts

 class AppService {
     static $inject = ['$http'];
     constructor(private $http: ng.IHttpService) {
     }
 
     public getBooks() {
         var url = "http://localhost/appservice/api/books";
         return this.$http({
             method: 'GET',
             url: url,
             headers: { "Accept": "application/json; odata=verbose" }
         });
     }
 }

App.ts

 class App {
     
     public static  app: ng.IModule
     constructor() {
       
         App.app = angular.module('app', []);
         App.app.controller("homeCtrl", Home);
         App.app.service('appService', AppService);
     }
 }
 new App();
 
 class Home {
     public lstBooks: Book[];
     static $inject = ['appService'];
     constructor(private appService: AppService) {
 
     }
 public async getBooks() {
         console.log('Before');
          await this.appService.getBooks().then(books =>{
              this.lstBooks = <Book[]>books.data;
             console.log(this.lstBooks);
         });
          console.log('After');
        
 
     }
 }
 

Index.html

 <div ng-controller="homeCtrl as vm">
 	<div ng-show="vm.show">{{vm.process}}</div>
 	<table>
 		<tr>
 			<th>ID</th>
 			<th>Title</th>
 			<th>Author</th>
 		</tr>
 
 		<tr ng-repeat="book in vm.lstBooks">
 			<td>{{book.Id}}</td>
 			<td>{{book.Title}}</td>
 			<td>{{book.AuthorName}}</td>
 		</tr>
 	</table>
 	<button ng-click="vm.getBooks()" type="button">Click</button>
 </div>
Category : TypeScript

Author Info

Krishna KV
 
Team Leader, Aspire Systems
 
Rate this article
 
Krishna K.V has been working in IT Industry for over 7+ years. He holds a Master Degree in Information Technology. He is more interested to learn and share new technologies, ...read more
 

Leave a comment