WebStorm 和 TypeScript 在 AngularJS 中找不到依赖项注入
WebStorm and TypeScript is not finding dependency injections in AngularJS
TypeScript 中的一个 AngularJS 组件:
class MyComponentCtrl {
static $inject = ['MyService'];
constructor(private MyService) {
MyService.testfn(55); // No error in typescript
}
}
class MyComponent implements ng.IComponentOptions {
constructor() {
this.controller = MyComponentCtrl;
this.template = 'hello';
}
}
angular
.module('app')
.component('MyComponent', new MyComponent());
TypeScript 中的 AngularJS 服务:
class MyService {
constructor() {
}
public testfn(age: number) {
console.log(age);
}
}
angular
.module('app')
.service('MyService', MyService);
当我在 WebStorm 中的 testfn
上点击 Cmd + 单击 时,找不到它 ("No decleration to go to")。此外,当我将 testfn
与无效参数一起使用时,TypeScript 编译器不会出错。
当我在 static $inject
中单击 MyService
时,WebStorm 正确找到了它。
我能否以某种不同的方式构造它以便 WebStorm 和 TypeScript 找到它?
注入的 MyService
是 any
,因此不会导致类型错误。
IDE 或 TypeScript 无法确定它是 MyService
服务的实例。此外,将其注入为 MyService
会产生误导,因为它是 class 实例,而不是 class 本身。
应导出一个 class:
export class MyService {...}
应该导入并指定为注入服务类型:
class MyComponentCtrl {
static $inject = ['MyService'];
constructor(private myService: MyService) {
myService.testfn(55);
}
}
TypeScript 中的一个 AngularJS 组件:
class MyComponentCtrl {
static $inject = ['MyService'];
constructor(private MyService) {
MyService.testfn(55); // No error in typescript
}
}
class MyComponent implements ng.IComponentOptions {
constructor() {
this.controller = MyComponentCtrl;
this.template = 'hello';
}
}
angular
.module('app')
.component('MyComponent', new MyComponent());
TypeScript 中的 AngularJS 服务:
class MyService {
constructor() {
}
public testfn(age: number) {
console.log(age);
}
}
angular
.module('app')
.service('MyService', MyService);
当我在 WebStorm 中的 testfn
上点击 Cmd + 单击 时,找不到它 ("No decleration to go to")。此外,当我将 testfn
与无效参数一起使用时,TypeScript 编译器不会出错。
当我在 static $inject
中单击 MyService
时,WebStorm 正确找到了它。
我能否以某种不同的方式构造它以便 WebStorm 和 TypeScript 找到它?
注入的 MyService
是 any
,因此不会导致类型错误。
IDE 或 TypeScript 无法确定它是 MyService
服务的实例。此外,将其注入为 MyService
会产生误导,因为它是 class 实例,而不是 class 本身。
应导出一个 class:
export class MyService {...}
应该导入并指定为注入服务类型:
class MyComponentCtrl {
static $inject = ['MyService'];
constructor(private myService: MyService) {
myService.testfn(55);
}
}