我在Angular 2.0.1中遇到了自定义提供程序的问题。我为我的http请求创建了一个自定义提供程序,以便在每个请求的头部添加一个参数,但是当我在我的提供程序中使用它们来获取用户服务时,我会收到错误。
HttpClient (自定义)
@Injectable()
export class HttpClient {
constructor(@Inject(Http) private _http: Http){}
}
UserServices
@Injectable()
export class UsersServices {
constructor(@Inject(HttpClient) private _http: HttpClient) {}
}
控制台错误:
无法解析UsersServices的所有参数:(?)。
tsconfig.json (typescript:2.0.3)
{
"compileOnSave": false,
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"mapRoot": "./",
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
"outDir": "../dist",
"sourceMap": true,
"typeRoots": [
"../node_modules/@types"
],
"types": [
"core-js",
"jasmine",
"node"
]
},
"files": [
"main.ts",
"typings.d.ts"
]
}
app.module.ts (angular:2.0.1)
@NgModule({
imports: [
CommonModule,
RouterModule,
HttpModule
],
exports: [],
declarations: [...],
providers: [ HttpClient, UsersServices ],
})
export class AppModule { }
答案 0 :(得分:1)
在角度核心调试几个小时之后,我找到了一个解决方案,我不知道它是否正确(最好),但看起来很有效。
app.module.ts (angular:2.0.1)
@NgModule({
imports: [
CommonModule,
RouterModule,
HttpModule
],
exports: [],
declarations: [...],
providers: [
{ provide:"appHttpClient", useClass:HttpClient }
, { provide:"appUsersServices", useClass:UsersServices }
]
})
export class AppModule { }
HttpClient (自定义)
@Injectable()
export class HttpClient {
constructor(@Inject(Http) private _http: Http){}
}
<强> UserServices 强>
@Injectable()
export class UsersServices {
constructor(@Inject("appHttpClient") private _http: HttpClient) {}
}