使用 TypeScript 返回 AngularJS $q 承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34237586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:09:34  来源:igfitidea点击:

Returning an AngularJS $q promise with TypeScript

angularjstypescriptangular-promisedeferred

提问by charcoalhobo

I have a service that wraps $http with my functions returning a deferred object.

我有一个服务,它用返回延迟对象的函数包装 $http。

My interface:

我的界面:

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

My 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;
    }
}

The compilation is failing with the following error:

编译失败并出现以下错误:

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

For reference, here is the IPromisedefinition from DefinitelyTyped. The IQService.defer()call returns an IDeferredobject, and then deferred.promisereturns IPromise object.

作为参考,这里是来自绝对类型的 IPromise定义。该IQService.defer()调用返回一个IDeferred对象,然后deferred.promise返回IPromise对象。

I'm not sure if I'm using the wrong definitions in my interface, or not returning the deferred object the same way. Any input would be greatly appreciated!

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

采纳答案by CaringDev

In your interface you defined a property getand in the service implementation it's a function get(). What you probably want is a function, so the interface should be:

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

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