FrozenPandaz / ng-universal-demo

171 stars 54 forks source link

How can you access location/url information on the server angular app #18

Closed rlavoie closed 7 years ago

rlavoie commented 7 years ago

How can I get access to what would have been window.location.host and window.location.pathname on the server within my angular app? I have seen provider examples just cant seem to grasp it or get anything working.

FrozenPandaz commented 7 years ago

You can get it from the Request object. It is available from the REQUEST injection token

https://github.com/angular/universal/blob/master/modules/ng-express-engine/README.md#using-the-request-and-response

rlavoie commented 7 years ago

@FrozenPandaz I have seen that but unsure where/how to inject that so my app.component can read the headers.

rlavoie commented 7 years ago

I was able to solve this with the REQUEST token as you suggested. I needed to inject with the injector, because I was getting a client side error.

import { REQUEST } from '@nguniversal/express-engine/tokens'; import { Injector } from '@angular/core';

ngOnInit() {

if (isPlatformBrowser(this.platformId)) {
  this.domainName = window.location.host + window.location.pathname;
}else if(isPlatformServer(this.platformId)){
  const req = this.injector.get(REQUEST);
  this.domainName = req.headers['host'] + req.originalUrl;
}

console.log(this.domainName)

}