angularjs - How can I handle an Angular promise in the controller using TypeScript -
i have service makes request data:
/// <reference path="../../typings/reference.ts" /> module app { 'use strict'; export class vehiclemakeservice { static $inject = ['$http']; constructor(private $http: ng.ihttpservice) {} getvehicles(): ng.ipromise<any> { return this.$http.get('https://api.edmunds.com/api/vehicle/v2/makes?state=used&year=2015&view=basic&fmt=json') .then(function(response) { return response.data; }); } } angular.module('app').service('vehiclemakeservice', vehiclemakeservice); }
this works expected, when attempt retrieve data in controller 'promise {$$state: object}'.
here controller:
/// <reference path="../../typings/reference.ts" /> module app { 'use strict'; interface isearchcontroller { vehicles: any; setvehicles(): void; } class searchcontroller implements isearchcontroller { vehicles: any; static $inject = ['vehiclemakeservice']; constructor(private vehiclemakeservice: vehiclemakeservice) { this.vehicles = {}; this.setvehicles(); } setvehicles(): void { this.vehicles = this.vehiclemakeservice.getvehicles(); console.log(this.vehicles); } } angular.module('app').controller('searchcontroller', searchcontroller); }
i tried resolving in controller:
setvehicles(): void { this.vehiclemakeservice.getvehicles().then(function(data) { this.vehicles = data; console.log(this.vehicles); }); }
but 'typeerror: cannot set property 'vehicles' of undefined'.
i handle kind of thing in resolve function in module config can't on occasion.
you can use arrow function ts/es6 this:
setvehicles(): void { this.vehiclemakeservice.getvehicles().then((data) => { this.vehicles = data; console.log(this.vehicles); }); }
btw. shouldn't use internal modules in ts bad ;)
you can check example skeleton application external modules angular 1.x , typescript here.
Comments
Post a Comment