如何使用TypeScript在控制器中处理Angular承诺

时间:2015-10-10 11:14:49

标签: angularjs http angular-promise resolve typescript1.4

我有一个服务请求某些数据:

/// <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);
}

这可以正常工作,但是当我尝试在控制器中检索数据时,我得到'Promise {$$ state:object}'。

这是控制器:

/// <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);
}

我尝试在控制器中解析它:

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

但后来我得到'TypeError:无法设置undefined'的属性'vehicle'。

我通常在模块配置的resolve函数中处理这种事情,但我不能在这种情况下。

2 个答案:

答案 0 :(得分:4)

您也可以使用TS / ES6中的箭头功能 像这样:

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

顺便说一句。你不应该在TS中使用内部模块那么糟糕;)

您可以使用外部模块Angular 1.x和TypeScript here检查我的示例骨架应用程序。

答案 1 :(得分:1)

由于getVehicles方法返回promise对象,因此您需要正确使用它,并且永远不要忘记HTTP请求的异步。此外,then中回调的上下文也会有所不同,因此您还需要使用它,例如使用bind方法:

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