我使用 index.ts 文件来封装导出,如 Angular 2 样式指南 (https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure) 中所述。
这在我编写的应用程序中运行良好,但出于某种原因,在我尝试注入(inject)另一项服务的一项服务中,这会导致奇怪的错误。
导出类:
import {Injectable} from "angular2/core";
@Injectable()
export class UserIds{
private _signature_id:string;
private _role_id:number;
get signature_id():string{
return this._signature_id;
}
set signature_id(id:string){
this._signature_id = id;
}
get role_id():number{
return this._role_id;
}
set role_id(id:number){
this._role_id = id;
}
}
index.ts 文件:
export {Midiate} from "./midiate.service/midiate.service";
export {HttpRest} from "./http_rest.service/http_rest.service";
export {UserIds} from "./user_ids.service/user_ids.service"
导致错误的代码(导入文件):
import {UserIds} from "../index";
import {Http} from 'angular2/http';
@Injectable()
export class HttpRest{
constructor(
public _http: Http,
public userIdsx: UserIds
){}
...
}
浏览器抛出的错误:
EXCEPTION: Cannot resolve all parameters for 'HttpRest'(Http, undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'HttpRest' is decorated with Injectable.
如您所见,UserIds 类在构造函数的参数中未定义。
更改对源文件的 UserIds 导入修复了问题:
import {UserIds} from "../user_ids.service/user_ids.service";
我仍然想在我的应用程序中使用 index.ts 作为所有其他服务和组件来保持旧的风格,并且也理解为什么会发生这种情况。
最佳答案
看起来您在 index.ts 中放置导出的顺序确实很重要!不确定这是不是错误,但无论如何...
用元数据装饰的类应该在 index.ts 的顶部如果其中一个注入(inject)另一个,则“另一个”应该在“一个”之上。
关于javascript - 使用 index.ts 文件导出类导致注入(inject)的构造函数中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37052975/