module app { 'use strict'; export class Vehic" /> module app { 'use strict'; export class Vehic" /> module app { 'use strict'; export class Vehic"/>

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

1.8k Views Asked by At

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.

2

There are 2 best solutions below

2
b091 On BEST ANSWER

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.

2
dfsq On

Since getVehicles method returns promise object you need to use it properly and never forget about asynchronousy of HTTP requests. Also context of the callback in then will be different so you also need to take of it, for example with bind method:

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