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>