ufk*_*ufk 6 typescript angular2-services angular
我正在编写一个带有typescript 2.0.3的角度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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在我身上使用那个可注射服务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 {
}
Run Code Online (Sandbox Code Playgroud)
所以在这里我将类启动到const并使用它.有没有一种方式注入凉爽和性感的方式?
例如,对于我的auth服务,我在构造函数中定义了它
constructor(@Inject(AppConfigService) appConfigService:AppConfigService)
Run Code Online (Sandbox Code Playgroud)
还有办法在这里做一件性感的事吗?或者只是按原样离开?
谢谢
您可以使用 APP_BASE_REF 工厂
providers: [
AppConfigService,
{
provide: APP_BASE_HREF,
useFactory: (config: AppConfigService) => {
return config.get('appBaseHref')
},
deps: [ AppConfigService ]
}
]
Run Code Online (Sandbox Code Playgroud)
将其添加AppConfigService到提供程序后,它就可以注入到工厂和身份验证服务中。无论如何,这通常是应该如何完成的。稍后如果说AppConfigService可能需要一些依赖项,它将通过注入系统来处理。
也可以看看:
@Inject。