使用可注入服务设置 APP_BASE_HREF 的配置

using injectable service to set configuration of APP_BASE_HREF

我正在用打字稿 2.0.3 编写一个 angular 2.1.0 项目。

我使用以下代码创建了一个 app-config 服务:

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

所以在这里我将 class 初始化为一个 const 并使用它。有没有办法以酷炫和性感的方式注射?

例如,对于我的身份验证服务,我在构造函数中定义了它

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 可能需要一些依赖项,它将通过注入系统处理。

另请参阅:

  • 关于您对 @Inject.
  • 的使用