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


Krishna KV
Team Leader, Aspire Systems
Published On :   24 Oct 2016
Visit Count
Today :  1    Total :   7441
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!


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>
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Protect Your SharePoint