Reputation: 1221
I am looking for a way to build an angular to production and be able to change the api url that is used.
For instance the first server with the api and the angular web has the url http://test.com.
On another server I will use the same code for the api and angular web but it has the url http://test2.com. I know how to fix this without rebuilding the api it.
But with Angular I only know how to do it if I change the url and then rebuild the code for the second server.
Is there a way to do this with for examle a settings-file?
Upvotes: 0
Views: 683
Reputation: 1066
First of all you have to create a service to manage the external configuration. We will get into that later for now let's go to your app.module.ts.
Here you should first import the service ( I will call it AppConfigService )
...
import { AppConfigService } from './services/app-config.service';
...
Then, before the @NgModule you must export a function that will initialize all the configurations:
export function initializeConfig( config: AppConfigService ) {
return () => config.load();
}
Now let's add this into the NgModule providers:
...
@NgModule({
declarations: [ ... ],
imports: [ ... ],
providers: [
...
AppConfigService, {
provide: APP_INITIALIZER,
useFactory: initializeConfig,
deps: [ AppConfigService ],
multi: true
},
...
],
bootstrap: [AppComponent]
})
...
Now let's take a look at the service we were talking about before:
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {Observable, throwError} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private config: Object;
constructor(
private _http: HttpClient
) {
this.config = {};
}
public getParam(key: any) {
// Returns a specific parameter
if (this.config[key]) {
return this.config[key];
} else if (!key) {
return this.config;
}
return false;
}
public load(): Promise<any> {
// This will load all the parameters
const confFile = 'path-to-your-json-file';
return new Promise((resolve, reject) => {
this._http.get(confFile).subscribe(
res => {
this.config = res;
resolve(true);
},
err => {
this.config = {};
reject(err);
}
)
});
}
}
This last part could be improved so much, this is just a quick example.
Finally we fetch the data from your components like this:
import {AppConfigService} from './services/app-config.service';
...
export class YourComponent {
public url: string;
constructor ( private _config: AppConfigService ) {
this.url = this._config.getParam('url1');
}
}
Edit: Now you can have a json file with configuration of your app, once it is in production the data will still be taken from this file so you can change it even after production
Upvotes: 1