【问题标题】:Returning an AngularJS $q promise with TypeScript使用 TypeScript 返回 AngularJS $q 承诺
【发布时间】:2016-03-18 04:41:36
【问题描述】:

我有一个服务,它用我的函数包装 $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<{}>'.

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

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

【问题讨论】:

  • 您也可以跳过所有this. = ;

标签: angularjs typescript angular-promise deferred


【解决方案1】:

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

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

【讨论】:

  • 哇,太尴尬了。这绝对是问题所在。感谢您的快速帮助!
猜你喜欢
  • 2016-09-18
  • 2013-09-11
  • 1970-01-01
  • 2015-06-20
  • 2014-06-27
  • 2017-12-21
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多