How to store the root url of api in angular 4 app?
After release of Angular 4.3 we have a possibility to use HttpClient interceprtors. The advantage of this method is avoiding of import/injection of API_URL is all services with api calls.
This is my basic implementation:
@Injectable()
export class ApiUrlInterceptor implements HttpInterceptor {
constructor(@Inject(API_URL) private apiUrl: string) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({url: this.prepareUrl(req.url)});
return next.handle(req);
}
private isAbsoluteUrl(url: string): boolean {
const absolutePattern = /^https?:\/\//i;
return absolutePattern.test(url);
}
private prepareUrl(url: string): string {
url = this.isAbsoluteUrl(url) ? url : this.apiUrl + '/' + url;
return url.replace(/([^:]\/)\/+/g, '$1');
}
}
InjectionToken declaration:
export const API_URL = new InjectionToken<string>('apiUrl');
Provider registration:
{provide: API_URL, useValue: environment.apiUrl}
{provide: HTTP_INTERCEPTORS, useClass: ApiUrlInterceptor, multi: true, deps: [API_URL]}
Environment.ts:
export const environment = {
production: false,
apiUrl: 'some-dev-api'
};
Where To Store Angular Configurations from Dave's Notebook Where To Store Angular Configurations
Because this is a frequent problem, because it is so often done incorrectly and because there is a great alternative, today I want to discuss where to store Angular configurations. You know, all that information that changes as you move from your local development environment to the Development, QA and Production servers?
There’s a place for that!
Wrong Place I know it is tempting, but the environment.ts and environment.prod.ts files were never meant for configuration information other than to tell the run-time you are running a production version of the code instead of developing the code locally. Yes, I know it is possible to create a file for your different environments and you can effectively use the file for your configuration information. But, just because you can, doesn’t mean you should.
In an ideal world, you would build a release candidate and place it on your Development server and then move it from there to QA and then to Production. You would never rebuild the application. You want to be absolutely sure that the code you tested in the Development environment is the code you ran in the QA environment and that the code you ran in the QA environment is the code that is running in the Production environment. You want to know for sure that the only possible reason why something isn’t working is because the configuration information is incorrect.
There are other ways to mitigate the risk, but they all involve recompiling the code and tagging your repository so you can get the same code back. This works when there isn’t a better way. But, there is a better way!
Where Instead? If we can’t put our configuration information in our code, where do we put it? Obviously external to your code. This leaves us several solutions. One is to create a static json file that gets copied into your dist directory when the code is deployed to each environment. Another place that I’ve see work is to place the code in a database. The advantage to the database method is that you can have one database that handles the configuration information for all of your applications and even all of your environments. Put a good administration GUI on top of it and you can change the configuration easily without having to deploy even a file.
Jumping The Hurdle Now that you’ve put your configuration information in an external location, you realize that you’ll need to make a GET request to retrieve that information. You may also quickly realize that you need that configuration information as soon as your application starts up. Maybe putting that information in an external file wasn’t such a great idea after all?
Well, not so fast!
There is a little known API feature in Angular that lets us load stuff up front and will actually wait until the loading has completed before continuing on with our code.
APP_INITIALIZER APP_INITIALIZER is a multi provider type that lets you specify a factory that returns a promise. When the promise completes, the application will continue on. So when you get to the place in your code where you need the configuration information, you can be sure it has been loaded. It’s pretty slick.
import { APP_INITIALIZER } from '@angular/core'
@NgModule({
....
providers: [
...
{
provide: APP_INITIALIZER,
useFactory: load,
multi: true
}
]
)
where load is a function that returns a function that returns a Promise. The promise function loads your configuration information and stores it in your application. Once your configuration has been loaded, you resolve the promise using resolve(true).
This last point is really important. If you get this wrong, the code won’t wait for this to finish loading before moving on. useFactory points to a function that returns a function that returns a Promise!
The multi: true thing is because APP_INITIALIZER allows multiple instances of this provider. They all run simultaneously, but the code will not continue beyond APP_INTITIALIZER until all of the Promises have resolved.
An example. Now, as a discussion point, let’s assume that you have a regular Angular CLI based project and you need to load in the base location of your REST endpoints. You might have a config.json file that looks something like this:
{
"baseUrl": "https://davembush.github.io/api"
}
You would create a different one of these for each of the environments you wanted to deploy to, and, as part of your deployment process, you would copy the appropriate file to config.json in the same location that you deploy all of your Angular CLI generated static files.
Basic App Initializer Now, the thing we want to do is to load this config file at runtime using APP_INITIALIZER. To do that, let’s add an APP_INITIALIZER provider to our app.module.ts file.
import { APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
function load() {
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [{
provide: APP_INITIALIZER,
useFactory: load,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
Full resulting code Just in case I left out a step or you are otherwise lost or maybe all you really care about is the code so you can copy and paste it.
import { APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ConfigService } from './config.service';
import { of, Observable, ObservableInput } from '../../node_modules/rxjs';
import { map, catchError } from 'rxjs/operators';
function load(http: HttpClient, config: ConfigService): (() => Promise<boolean>) {
return (): Promise<boolean> => {
return new Promise<boolean>((resolve: (a: boolean) => void): void => {
http.get('./config.json')
.pipe(
map((x: ConfigService) => {
config.baseUrl = x.baseUrl;
resolve(true);
}),
catchError((x: { status: number }, caught: Observable<void>): ObservableInput<{}> => {
if (x.status !== 404) {
resolve(false);
}
config.baseUrl = 'http://localhost:8080/api';
resolve(true);
return of({});
})
).subscribe();
});
};
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [{
provide: APP_INITIALIZER,
useFactory: load,
deps: [
HttpClient,
ConfigService
],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }