I need to get the full base URL (e.g. http://localhost:5000 or https://productionserver.com) of my Angular 2 app so that I can pass it along to a 3rd party service in the co
You’ll find that all content coming from Http requests won’t be pre-rendered: it’s because Universal needs absolute URLs.
As your development and production server won’t have the same URL, it’s quite painful to manage it on your own.
My solution to automate this : using the new HttpClient interceptor feature of Angular 4.3, combined with the Express engine.
The interceptor catches all requests when in server context to prepend the full URL.
import { Injectable, Inject, Optional } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from'@angular/common/http';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject('serverUrl') protected serverUrl: string) {}
intercept(req: HttpRequest, next: HttpHandler) {
const serverReq = !this.serverUrl ? req : req.clone({
url: ``${this.serverUrl}${req.url}``
});
return next.handle(serverReq);
}
}
Then provide it in your AppServerModule :
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { UniversalInterceptor } from './universal.interceptor';
@NgModule({
imports: [
AppModule,
ServerModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: UniversalInterceptor,
/* Multi is important or you will delete all the other interceptors */
multi: true
}],
bootstrap: [AppComponent]
})
export class AppServerModule {}
Now you can use Express engine to pass the full URL to Angular, just update your server.js :
function angularRouter(req, res) {
res.render('index', {
req,
res,
providers: [{
provide: 'serverUrl',
useValue: `${req.protocol}://${req.get('host')}`
}]
});
}