@Inject custom provider in Angular 2.0.1

2020-02-07 05:46发布

问题:

i have issue with my custom provider in 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.

HttpClient (custom)

@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: (?).

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 { }

回答1:

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.

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 (custom)

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

UserServices

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