Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get full url in Angular?

My app takes advantage of Angular Universal and I'd like to get the full path of the current url in an Angular component. I think I have to use the window object where I may need to inject the window or maybe the better option is to simply check if it's in the browser. Are there any cleaner solutions utilizing Angular's API?

  url: string;

  constructor(private router: Router) { }

  ngOnInit() {
    this.router.events.subscribe((val) => {
      this.url = `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
    });
  }

Edit: The question I'm asking is how to get the full url in a way that is compliant with Angular Universal

like image 789
Zack Lucky Avatar asked Mar 28 '26 22:03

Zack Lucky


1 Answers

If you are using Express, you can inject the url from express to your component

Step #1: modify your node server to pass the url you want

//Get index.html file contents from dist/browser/index.html
const DIST_FOLDER = join(process.cwd(), 'dist'); 
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();


app.engine('html', (_, options, callback) => {
var fullUrl = options.req.protocol + '://' + options.req.get('host') + options.req.originalUrl;

  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.url,
    // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: 'serverUrl',
        useValue: fullUrl
      }
    ]
  }).then(html => {
    callback(null, html);
  });
});

Step #2: In your component/service, add an optionnal parameter

constructor(@Inject(PLATFORM_ID) private platformId: Object, @Optional() @Inject('serverUrl') protected serverUrl: string)
{
 // Here, this.serverUrl will have a value only when using angular universal
like image 150
David Avatar answered Apr 03 '26 16:04

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!