'how to replace API url with Run Time Json File Angular 10
currently I am using below structure to get API url
My environment.ts
export const environment = {
apiUrl: 'https://12.8.0.1:8282/'
};
I am trying to get apiUrl Using in the Run Time. I did that implementation correctly.
config.service
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable( )
export class ConfigService {
private appConfig;
constructor(private http: HttpClient) { }
loadConfig(){
return this.http.get('./assets/config.json')
.toPromise()
.then(res =>{
this.appConfig = res;
console.log(res);
});
}
getConfig(){
return this.appConfig;
}
}
App module
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AuthGuard } from './auth.guard';
import { NgSelectModule } from '@ng-select/ng-select';
import { ConfigService } from './config.service';
//import {EndDateValidatorDirective} from '../app/layout/admin/holidays/EndDateValidatorDirective'
export const createTranslateLoader = (http: HttpClient) => {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
};
const appConfig = (config: ConfigService) =>{
return() =>{
return config.loadConfig();
}
}
@NgModule({
declarations: [
AppComponent,
],
imports: [
[
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule, NgSelectModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient]
}
}),
AppRoutingModule
]
],
providers: [ConfigService,{
provide:APP_INITIALIZER,
useFactory:appConfig,
multi: true,
deps:[ConfigService]
},AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
I run the project and this is working well. My function executed in the Run time successfully.
Now I need to use this config.json file (inside assets folder) and get that apiUrl. How i do it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

