【发布时间】: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