从桶中导入服务(https://angular.io/docs/ts/latest/glossary.html#!#barrel)时,我遇到了依赖注入问题。Angular 2 - 依赖注入和桶装
我所面临的问题是这样的:
使用角准则,在应用程序中有一个核心筒,然后每个文件夹桶,这些由具有每个文件夹中的index.ts实现。核心index.ts引用每个文件夹中的所有内容,然后每个文件夹引用特定文件。
芯index.ts
...
export * from './test/index';
测试index.ts
...
export * from './my-service.service';
代码
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时,不会创建元数据。这并没有解决我的问题。在尝试了几件事情之后,我试着改变导入以获得如下所示的服务,并且不抛出错误。
成功输入:
3210或
import { MyService } from '../../core/test';
我不知道,如果有一个问题在我的应用程序index.ts文件或可能是文件结构本身是错误的,但从我所看到的他们工作得很好。想知道为什么这个特殊的import
是有所作为。
它是否将导入更改为常规导入语句? – rinukkusu
是的,我会将它添加到问题中。没有意识到,它不明确! :) –
我认为有人提到,在桶出口顺序可能会导致问题。 –