我正在编写一个带有typescript 2.0.3的角度2.1.0项目.
import { Injectable } from '@angular/core'; @Injectable() export class AppConfigService { public config: any = { auth0ApiKey: '<API_KEY>',auth0Domain: '<DOMAIN>',auth0CallbackUrl: '<CALLBACK_URL>',appBaseHref: '/' } constructor() {} /* Allows you to update any of the values dynamically */ set(k: string,v: any): void { this.config[k] = v; } /* Returns the entire config object or just one value if key is provided */ get(k: string): any { return k ? this.config[k] : this.config; } }
现在我想在app-module.ts上使用该可注入服务来设置APP_BASE_HREF提供程序.
import { browserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { AppComponent } from './app/app.component'; import { HelpComponent } from './help/help.component'; import { WelcomeComponent } from './welcome/welcome.component'; import {APP_BASE_HREF} from "@angular/common"; import { MaterialModule } from "@angular/material"; import { AUTH_PROVIDERS } from "angular2-jwt"; import { RouterModule } from "@angular/router"; import {AppConfigService} from "app-config.service"; const appConfigService = new AppConfigService(); @NgModule({ declarations: [ AppComponent,HelpComponent,WelcomeComponent ],imports: [ browserModule,FormsModule,HttpModule,MaterialModule.forRoot(),RouterModule.forRoot([ { path: "",redirectTo:"welcome",pathMatch:"full"},{ path: "welcome",component: WelcomeComponent },{ path: "help",component: HelpComponent},{ path: "**",redirectTo:"welcome"} ]) ],providers: [AUTH_PROVIDERS,{provide: APP_BASE_HREF,useValue:appConfigService.get('appBaseHref')}],bootstrap: [AppComponent] }) export class AppModule { }
所以在这里我将类启动到const并使用它.有没有一种方式注入凉爽和性感的方式?
例如,对于我的auth服务,我在构造函数中定义了它
constructor(@Inject(AppConfigService) appConfigService:AppConfigService)
还有办法在这里做一件性感的事吗?或者只是按原样离开?
谢谢
解决方法
您可以将工厂用于APP_BASE_REF
providers: [ AppConfigService,{ provide: APP_BASE_HREF,useFactory: (config: AppConfigService) => { return config.get('appBaseHref') },deps: [ AppConfigService ] } ]
将AppConfigService添加到提供程序后,可以将其注入工厂和身份验证服务.这通常是应该如何完成的.稍后如果说AppConfigService可能需要一些依赖,它将通过注入系统处理.
也可以看看:
> What is the difference between @Inject vs constructor injection as normal parameter in Angular 2?关于你对@Inject的使用.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。