angularjs - 使用 TypeScript 返回 AngularJS $q promise

标签 angularjs typescript angular-promise deferred

我有一项服务将 $http 与返回延迟对象的函数包装在一起。

我的界面:

export interface MyServiceScope {
    get: ng.IPromise<{}>;
}

我的类(class):

export class MyService implements MyServiceScope {

    static $inject = ['$http', '$log'];

    constructor(private $http: ng.IHttpService,
                private $log: ng.ILogService,
                private $q: ng.IQService) {
        this.$http = $http;
        this.$log = $log;
        this.$q = $q;
    }

    get(): ng.IPromise<{}> {
        var self = this;
        var deferred = this.$q.defer();

        this.$http.get('http://localhost:8000/tags').then(
            function(response) {
                deferred.resolve(response.data);
            },
            function(errors) {
                self.$log.debug(errors);
                deferred.reject(errors.data);
            }
        );

        return deferred.promise;
    }
}

编译失败,错误如下:

myservice.ts(10,18): error TS2420: Class 'MyService' incorrectly implements interface 'MyServiceScope'.
    Types of property 'get' are incompatible.
        Type '() => IPromise<{}>' is not assignable to type 'IPromise<{}>'.
            Property 'then' is missing in type '() => IPromise<{}>'.

供引用,here is the IPromise来自 DefinitelyTyped 的定义。 IQService.defer() 调用返回一个 IDeferred 对象,然后 deferred.promise 返回 IPromise 对象。

我不确定我是否在我的界面中使用了错误的定义,或者没有以相同的方式返回延迟对象。任何输入将不胜感激!

最佳答案

在您的界面中,您定义了一个属性get,在服务实现中它是一个函数get()。你可能想要的是一个函数,所以接口(interface)应该是:

export interface MyServiceScope {
    get(): ng.IPromise<{}>;
}

关于angularjs - 使用 TypeScript 返回 AngularJS $q promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34237586/

相关文章:

javascript - 动态更新指令 (1.2 rc3)

javascript - ng-repeat 中的 ng-if

angularjs - 在 promise 解决/拒绝后返回 bool 值?

javascript - 如何使用 Angular.js 和 PHP 按字母顺序显示列表

html - 检查 ngStyle 内部函数是否有返回值

typescript - 如何使用动态键使 TypeScript 类型检查对象文字?

reactjs - 使用 React-leaflet version3 的传单 map 上的自定义按钮

javascript - 链接多个 Promise(处理回调)

javascript - angularjs:链 promise 返回一个 promise 而不是一个对象

javascript - Angularjs - 将服务代码移动到另一个文件