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

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

问题描述

我在 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.

HttpClient(自定义)

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

用户服务

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

控制台错误:

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

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

tsconfig.json(打字稿: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)

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

推荐答案

在 angular 核心调试几个小时后,我找到了一个解决方案,我不知道它是否正确(最好),但它看起来很有效.

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)

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

用户服务

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

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

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