Using the injection service to configure APP_BASE_HREF

I am writing an angular 2.1.0 project with typescript 2.0.3.

I created the app-config with the following code:

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

now I want to use this injection service on my app-module.ts to install the APP_BASE_HREF provider.

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

so here I initiate the class in const and use it. is there a way to inject in a cool and sexy way?

for example, for my auth service, I defined it in the constructor

 constructor(@Inject(AppConfigService) appConfigService:AppConfigService) 

Is there a way to do a sexy thing here too? or just leave it as it is?

thanks

+6
source share
1 answer

You can use factory for APP_BASE_REF

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

Once you add the AppConfigService to the providers, it makes it injectable for both the factory and the auth service. As a rule, this is how it should be done. Later, if you say that AppConfigService may require some dependencies, it will be processed through the injection system.

See also:

+2
source

All Articles