简体   繁体   English

@Inject Angular 2.0.1 中的自定义提供程序

[英]@Inject custom provider in Angular 2.0.1

i have issue with my custom provider in Angular 2.0.1.我在 Angular 2.0.1 中的自定义提供程序有问题。 I create a custom provider for my http request to add in header a parameter on every request, but when i use them on my provider for user services i get error.我为我的 http 请求创建了一个自定义提供程序,以便在每个请求的标头中添加一个参数,但是当我在我的用户服务提供程序上使用它们时,我收到错误。

HttpClient (custom) HttpClient (自定义)

@Injectable()
export class HttpClient {
    constructor(@Inject(Http) private _http: Http){}
}

UserServices用户服务

@Injectable()
export class UsersServices {
    constructor(@Inject(HttpClient) private _http: HttpClient) {}
}

Error in console:控制台中的错误:

Can't resolve all parameters for UsersServices: (?).无法解析 UsersServices 的所有参数:(?)。

tsconfig.json (typescript:2.0.3) 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 (angular:2.0.1) app.module.ts (角度:2.0.1)

 @NgModule({
     imports: [
      CommonModule,
      RouterModule,
      HttpModule
    ],
    exports: [],
    declarations: [...],
    providers: [ HttpClient, UsersServices ],
})
export class AppModule { }

After of some hours debugging in the core of angular, i found a solution, i don't know if it is correct (best) but it's look works.在 angular 核心调试几个小时后,我找到了一个解决方案,我不知道它是否正确(最好),但它看起来很有效。

app.module.ts (angular:2.0.1) app.module.ts (角度:2.0.1)

 @NgModule({
     imports: [
      CommonModule,
      RouterModule,
      HttpModule
    ],
    exports: [],
    declarations: [...],
    providers: [ 
        { provide:"appHttpClient", useClass:HttpClient }
      , { provide:"appUsersServices", useClass:UsersServices }
   ]
})
export class AppModule { }

HttpClient (custom) HttpClient (自定义)

@Injectable()
export class HttpClient {
    constructor(@Inject(Http) private _http: Http){}
}

UserServices用户服务

@Injectable()
export class UsersServices {
    constructor(@Inject("appHttpClient") private _http: HttpClient) {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM