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

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

问题描述

我有一个服务,它包装了$ 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;
    }
}

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

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

作为参考,这是IPromise 从DefinitelyTyped中定义. 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 promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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