【发布时间】:2017-02-04 22:06:56
【问题描述】:
我在 Angular 2.0.1 中的自定义提供程序存在问题。我为我的 http 请求创建了一个自定义提供程序,以便在每个请求的标头中添加一个参数,但是当我在我的提供程序上将它们用于用户服务时,我得到了错误。
HttpClient(自定义)
@Injectable()
export class HttpClient {
constructor(@Inject(Http) private _http: Http){}
}
用户服务
@Injectable()
export class UsersServices {
constructor(@Inject(HttpClient) private _http: HttpClient) {}
}
控制台出错:
无法解析用户服务的所有参数:(?)。
tsconfig.json(打字稿: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(角度:2.0.1)
@NgModule({
imports: [
CommonModule,
RouterModule,
HttpModule
],
exports: [],
declarations: [...],
providers: [ HttpClient, UsersServices ],
})
export class AppModule { }
【问题讨论】:
-
当
HttpClient为@Injectable()时,您不需要使用@Inject(HttpClient) -
在 Angular 文档中:建议:将 @INJECTABLE() 添加到每个服务类 我们建议将 @Injectable() 添加到每个服务类,即使是那些没有依赖关系的服务类因此,在技术上不需要它。原因如下: 面向未来:以后添加依赖项时无需记住@Injectable()。一致性:所有服务都遵循相同的规则,我们不必怀疑为什么缺少装饰器。
-
正确。我指的是您的构造函数中的
@Inject(HttpClient)。当服务为@Injectable()时,您不需要使用@Inject(),而且我认为无论如何使用它都会有问题。
标签: angular typescript dependency-injection