在Angular 2 DIC中处理服务配置
来自Java背景的我很难理解Angular的一些内容,特别是依赖注入机制。这和我习惯的完全不同。现在,我正试图了解如何将配置变量注入到我正在创建的服务中:在Angular 2 DIC中处理服务配置,angular,Angular,来自Java背景的我很难理解Angular的一些内容,特别是依赖注入机制。这和我习惯的完全不同。现在,我正试图了解如何将配置变量注入到我正在创建的服务中: @Injectable() export class MyBackendService { constructor(url: string, version: string, token: string, secret: string) { } } 所有这些字符串都存储在我的环境中。{env}.ts文件中。但我不知道如何告诉Angu
@Injectable()
export class MyBackendService {
constructor(url: string, version: string, token: string, secret: string) { }
}
所有这些字符串都存储在我的
环境中。{env}.ts
文件中。但我不知道如何告诉Angular获取这些变量并注入到我的服务类中。有人对这种惯用方法有什么建议吗?为了从DIC注入依赖项,应该在其中注册依赖项
在DIC中注册可注射实体的方法是通过@NgModule。然后从使用它的模块中导入这个
要向DIC注册服务或值,它应位于NGD模块的提供商阵列中
在这个具体示例中(如果您需要将其添加到DIC中),我更愿意将配置值注入后端服务,该服务所需的所有数据取自应用程序的配置文件:
1配置
- 配置模块
import { NgModule } from '@angular/core'; import { CONFIG } from "..."; @NgModule({ providers: [ { provide: CONFIG, useValue: CONFIG } ] }) export class ConfigModule{}
export const CONFIG = { endpoint: { service1: { url: 'http://api.your-app.com/service1/', withCredentials: true, ... }, } }
- 配置值
import { NgModule } from '@angular/core'; import { CONFIG } from "..."; @NgModule({ providers: [ { provide: CONFIG, useValue: CONFIG } ] }) export class ConfigModule{}
export const CONFIG = { endpoint: { service1: { url: 'http://api.your-app.com/service1/', withCredentials: true, ... }, } }
- 模块:
import { NgModule } from '@angular/core'; import { Service1 } from "..."; import { CONFIG } from "..."; import { ConfigModule } from "..."; @NgModule({ imports: [ ConfigModule // Import the config module to make the config available for the services in this module ] providers: [ { provide: Service1 // Register your service in the DIC the one that performs the requests to that server endpoint, useFactory: (config) => new Service1(config), deps:[ CONFIG ] } ] }) export class ApiModule{}
- 服务
import { NgModule } from '@angular/core'; export class Service1{ private _endpointUrl:string; constructor(config) { this._endpointUrl = config.endpoint.service1.url; } }
import {CONFIG} from '...'; export class Service1{ private config; constructor() { this._config = CONFIG; } }
import { NgModule } from '@angular/core';
import { ApiModule } from "...";
@NgModule({
imports: [
ApiModule
]
...
})
export class AppComponent{}
那么你的注射链就会
AppComponent <- Service1 <- CONFIG
稍后,如果需要从端点加载,则可以使用您在应用程序中使用的模块加载器(SystemJS、Webpack…)解决该问题
如果您想在不重新加载浏览器的情况下更新应用程序配置,则会显示此选项的反面。在这种情况下,我认为配置值应由DIC提供的配置服务提供
希望这能有所帮助。Hmm,制作另一个服务来确定合适的环境,获取正确的值并将这些属性提供给构造函数如何?然后是谁提供该服务?嗯,在您的情况下,我要做的是将环境数据存储在某个JSON文本文件中,例如,
environment.{env}.JSON
,然后在EnvironmentService
(我刚刚起了这个名字)中确定环境,读取适当的JSON数据,设置EnvironmentService
的属性,然后将EnvironmentService
注入MyBackendService
。我正在使用angular cli的环境文件:这看起来很简单。按照他所做的做,在他将所有内容放在一起的TypeScript文件中,基本上只需删除decorator并将该TypeScript文件用作服务。确保在AppModule中提供该服务,然后将其注入构造函数中的MyBackendService
。然后根据该服务提供的值设置MyBackendService
的值。