Angular 7 : How can i get the complete URL of the current page
The universal server side isn't aware of the window.location.
The express server on the other hand knows the url from the request that was being sent to the server side.
So we need to inject the request url from express into angular..
server.ts
let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();
app.engine('html', (_, options, callback) => {
renderModuleFactory(AppServerModuleNgFactory, {
document: template,
url: options.req.url,
extraProviders: [
{ provide: 'requestUrl', useFactory: () => options.req.url, deps: [] }, // 1. set up the provider for the url
provideModuleMap(LAZY_MODULE_MAP)
]
}).then(html => {
callback(null, html);
});
});
..in order to retrieve it where we need it..
url-logger.ts
class UrlLogger {
constructor(
private window: Location,
private injector: Injector, // 2. we need the injector to ..
@Inject(PLATFORM_ID) private platformId: string,
) { }
public log() {
if (isPlatformServer(this.platformId)) {
const requestUrl = this.injector.get('requestUrl'); // 3. ..retrieve the injected url
console.log('server greets you via ' + requestUrl)
} else {
console.log('browser says hello from ' + window.location.href)
}
}
}