【问题标题】:using injectable service to set configuration of APP_BASE_HREF使用可注入服务设置 APP_BASE_HREF 的配置
【发布时间】:2016-10-15 15:56:22
【问题描述】:

我正在使用 typescript 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 {
}

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

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

constructor(@Inject(AppConfigService) appConfigService:AppConfigService)

这里也有做性感的方法吗?还是保持原样?

谢谢

【问题讨论】:

    标签: angular typescript angular2-services


    【解决方案1】:

    您可以为 APP_BASE_REF 使用工厂

    providers: [
      AppConfigService,
      {
        provide: APP_BASE_HREF,
        useFactory: (config: AppConfigService) => {
          return config.get('appBaseHref')
        },
        deps: [ AppConfigService ]
      }
    ]
    

    AppConfigService 添加到提供程序后,它就可以注入工厂和身份验证服务。这通常是无论如何都应该这样做的。后面如果说AppConfigService可能需要一些依赖,会通过注入系统处理。

    另见:

    【讨论】:

    • 如果这不起作用,我不知道如何接受这个答案。发帖前你试过了吗?
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多