AngularJS TypeScript服务错误

3

我在尝试向一个模块添加服务时遇到了这个错误。有人能帮忙指出问题所在吗?

Angular 版本为1.5.11,TypeScript 版本为2.2.2。

ERROR in ./source/mainModule.ts
(185,33): error TS2345: Argument of type 'typeof AwesomeService ' is not 
assignable to parameter of type 'Injectable<Function>'.
Type 'typeof AwesomeService ' is not assignable to type '(string | Function)[]'.
Property 'push' is missing in type 'typeof AwesomeService '.

这里是我尝试添加服务的地方。
export default angular.module('iris.service', [])
    /* This line throws the error --> */.service('awesomeService', AwesomeService);

在另一个文件中,这是我如何创建该服务的方式。
export class AwesomeService extends OtherClass {

    private static $inject = ['configService'];

    constructor() {
        super();
    }
}

更新:

我发现如果我将AwesomeService更改为一个函数并导出,它就可以正常工作。有没有办法使用类来实现服务?看起来@types/angular指定angular.module.service的第二个参数应该是字符串或函数。


如果您像这样大写“AwesomeService”,该怎么办: export default angular.module('iris.service', []).service('AwesomeService', AwesomeService); - MMachinegun
2
那不会改变任何事情。那可以是任意名称。 - Spencer
好的,稍后我可能需要再考虑一下。 - MMachinegun
@Spencer 是的,使用相同的大小写来注册名称和注册值的唯一优点是,您可以编写 .module('iris.service', []).service({ AwesomeService }) 这是一个方便的简写,特别是如果您使用某些注册模式。 - Aluan Haddad
1个回答

2

是的,你可以做到你想要的,只需要写更少的代码。

@types/angular 中的类型声明包括以下内容

declare global {
    interface Function {
        $inject?: ReadonlyArray<string>;
    }
}

这增强了Function类型的声明。 添加一个可选属性$inject,以允许在类型安全和声明性的方式下向类和函数添加干净、易读的AngularJS DI注释,而无需使用不美观的类型断言。

请注意,所有的类和函数实际上都是函数。

你的类的问题在于,虽然上面的Function类型增强声明了$inject是可选的,但它并没有说明当指定了$inject时,它可能是private的。

事实上,从语义上讲,它非常不是私有的,因为它被AngularJS框架和其他工具读取。

要解决这个问题,只需写

export class AwesomeService extends OtherClass {

    static $inject = ['configService']; // no private here.

    constructor() {
        super();
    }
}

更详细的答案是,如果一个类型声明了一个私有成员(为此需要它是一个类),并且该私有成员与另一个类型中的公共成员具有相同的名称(所有接口成员都是公共的),则认为这两个类型在结构上不兼容。
不幸的是,错误有点晦涩。`private $inject` 声明会导致类型检查器立即移除接受 `Function` 类型值的 `service` 重载。然后尝试使用接受 `Array` 类型值的 `service` 重载,但却失败了。

1
太棒了。我想我在考虑转换后的JavaScript,其中public/private都变成相同的AwesomeService.$inject。谢谢你帮我记起TypeScript更聪明! - Spencer
很高兴能帮忙 :) - Aluan Haddad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接