使用 TypeScript 返回 AngularJS $q 承诺

编程入门 行业动态 更新时间:2024-10-27 12:34:46
本文介绍了使用 TypeScript 返回 AngularJS $q 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个服务,它用返回延迟对象的函数包装 $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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 10:03:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1000521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:TypeScript   AngularJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!