從桶中導入服務(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
是的,我會將它添加到問題中。沒有意識到,它不明確! :) –
我認爲有人提到,在桶出口順序可能會導致問題。 –