angularjshttpangular-promiseresolvetypescript1.4

How can I handle an Angular promise in the controller using TypeScript


I have a Service that makes a request for some 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 as expected, however when I attempt to retrieve the data in the controller I get 'Promise {$$state: object}'.

Here is the 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 it in the controller:

setVehicles(): void {
        this.vehicleMakeService.getVehicles().then(function(data) {
            this.vehicles = data;
            console.log(this.vehicles);
        });
    }

But then I get 'TypeError: Cannot set property 'vehicles' of undefined'.

I normally handle this kind of thing in the resolve function in the module config but I can't on this occasion.


Solution

  • You can also use arrow function from TS/ES6 like this:

    setVehicles(): void {
        this.vehicleMakeService.getVehicles().then((data) => {
            this.vehicles = data;
            console.log(this.vehicles);
        });
    }
    

    btw. you shouldn't use internal modules in TS its so bad ;)

    you can check my example skeleton application with external modules Angular 1.x and TypeScript here.