Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

typescript - @Inject custom provider in Angular 2.0.1

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 { }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...