从桶(https://angular.io/docs/ts/latest/glossary.html#!#barrel)导入服务时,我遇到了依赖注入的问题 .
我遇到的问题是:
使用Angular指南,在应用程序中有一个核心桶,然后是每个文件夹的桶,这些是通过在每个文件夹中有一个index.ts来实现的 . 核心index.ts引用每个文件夹中的所有内容,然后每个文件夹引用特定文件 .
core index.ts
...
export * from './test/index';
test index.ts
...
export * from './my-service.service';
Code
import { MyService } from '../../core';
...
@Injectable()
export class AuthGuard implements CanActivate {
isValidSession: boolean = false;
errorMessage: any;
constructor(
private myService: MyService
) { }
canActivate(
// Not using but worth knowing about
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
return this.myService.doSomething();
}
}
上面的代码导致以下错误:
Uncaught Cannot resolve all parameters for 'AuthGuard'(undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthGuard' is decorated with Injectable.
查看代码我没有发现缺少 @Injectable
注释的任何问题 . 实际上,相同的服务正在其他组件中使用,并使用核心index.ts导入 .
一个article我发现建议应该使用构造函数中的 @Inject
,因为有时当TypeScript转换为JavaScript时,不会创建元数据 . 在我的案例中,这并没有解决问题 . 尝试了几件事后,我只是尝试更改导入以获得如下所示的服务,并且没有抛出错误 .
Successful importation:
import { MyService } from '../../core/test/my-service.service';
要么
import { MyService } from '../../core/test';
我在我的应用程序中的index.ts文件中存在一个问题,或者文件结构本身可能是错误的,但从我可以看到它们工作正常 . 想知道为什么这个特殊的 import
正在发挥作用 .
2 回答
订单确实如上所述!不确定这是不是一个bug但是无论如何......
所以,在我看来,用元数据装饰的类应该在索引的顶部 . 如果其中一个注入另一个,则“另一个”应该在“一个”之上 .
我有完全相同的问题,并且Günter是正确的:桶中
export
的顺序确实很重要 .在我的情况下,我在我的桶里:
这导致了你看到的同样的错误 . 将服务放在使用它的组件之前解决了问题:
我没有找到任何关于此的文档,但我发现这种行为肯定不太理想,因为
这是隐含的
没有记录
错误消息没有给出任何关于如何修复它的提示