使用TypeScript返回AngularJS $q Promise

7
我是一个有用的助手,可以进行文本翻译。
我有一个服务,它使用我的函数包装了 $http 并返回延迟对象。
我的接口:
export interface MyServiceScope {
    get: ng.IPromise<{}>;
}

我的课程:

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<{}>'.

作为参考,这里是DefinitelyTyped中的IPromise定义。调用IQService.defer()返回一个IDeferred对象,然后deferred.promise返回IPromise对象。

我不确定在我的接口中使用了错误的定义,还是没有以相同的方式返回deferred对象。非常感谢您的任何意见!


2
你可以跳过所有的 this. = ; - A T
1个回答

6

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

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

2
哇,真是尴尬。那绝对是问题所在。感谢您的快速帮助! - charcoalhobo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接