使用 TypeScript 返回 AngularJS $q 承诺 [英] Returning an AngularJS $q promise with TypeScript

查看:38
本文介绍了使用 TypeScript 返回 AngularJS $q 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的界面:

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

作为参考,我承诺> 来自绝对类型的定义.IQService.defer() 调用返回一个 IDeferred 对象,然后 deferred.promise 返回 IPromise 对象.

For reference, here is the IPromise definition from DefinitelyTyped. The IQService.defer() call returns an IDeferred object, and then deferred.promise returns IPromise object.

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

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!

推荐答案

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

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

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

这篇关于使用 TypeScript 返回 AngularJS $q 承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆