@注入Angular 2.0.1中的自定义提供程序 [英] @Inject custom provider in Angular 2.0.1

查看:115
本文介绍了@注入Angular 2.0.1中的自定义提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 2.0.1中与我的自定义提供商有问题。我为我的http请求创建一个自定义提供程序,在每个请求中添加一个参数,但是当我在我的提供者上使用它们进行用户服务时,我收到错误。

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.

strong> HttpClient

HttpClient (custom)

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

UserServices

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

控制台错误:


无法解析UsersServices的所有参数:(?)。

Can't resolve all parameters for UsersServices: (?).

tsconfig.json (typescript:2.0.3)

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 (有角度:2.0.1)

app.module.ts (angular:2.0.1)

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


推荐答案

之后的som e小时调试的核心是角度,我找到一个解决方案,我不知道它是否是正确的(最好的),但它看起来很有效。

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 (有角度:2.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){}
}

strong> UserServices

UserServices

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

这篇关于@注入Angular 2.0.1中的自定义提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆