【问题标题】:@Inject custom provider in Angular 2.0.1@Inject Angular 2.0.1 中的自定义提供程序
【发布时间】:2017-02-04 22:06:56
【问题描述】:

我在 Angular 2.0.1 中的自定义提供程序存在问题。我为我的 http 请求创建了一个自定义提供程序,以便在每个请求的标头中添加一个参数,但是当我在我的提供程序上将它们用于用户服务时,我得到了错误。

HttpClient(自定义)

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

用户服务

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

控制台出错:

无法解析用户服务的所有参数:(?)。

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

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

【问题讨论】:

  • HttpClient@Injectable() 时,您不需要使用@Inject(HttpClient)
  • 在 Angular 文档中:建议:将 @INJECTABLE() 添加到每个服务类 我们建议将 @Injectable() 添加到每个服务类,即使是那些没有依赖关系的服务类因此,在技术上不需要它。原因如下: 面向未来:以后添加依赖项时无需记住@Injectable()。一致性:所有服务都遵循相同的规则,我们不必怀疑为什么缺少装饰器。
  • 正确。我指的是您的构造函数中的@Inject(HttpClient)。当服务为@Injectable() 时,您不需要使用@Inject(),而且我认为无论如何使用它都会有问题。

标签: angular typescript dependency-injection


【解决方案1】:

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

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

【讨论】:

  • 这解决了我的问题。这种方法是否类似于为要注入主服务的服务使用别名?
猜你喜欢
  • 1970-01-01
  • 2016-04-23
  • 2021-03-14
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 2010-12-12
  • 2021-11-21
相关资源
最近更新 更多