Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular universal - get current url in server side

The question may simple but I couldn't find working solution anywhere. I have a website where I have Angular SSR setup and want to get the current url in one of my Angular components. I have gone thru multiple sites and understood that I had to pass host information from universal server and get the same in Angular component.

My code snipet from server.ts file where I am passing the host information

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, {
      req,
      providers: [
        { provide: APP_BASE_HREF, useValue: req.baseUrl },
        { provide: 'host', useValue: req.get('host') }, // sending host name in provider
      ],
    });
  });

my host.ts file is as below,

import { InjectionToken } from '@angular/core';
export const HOST_ID = new InjectionToken<string>('host');

And this is how, I tried to get the host name in app component.ts which always gives me null value.

export class AppComponent implements OnInit {
  isLoading: boolean = false;
  constructor(
    @Optional() @Inject(HOST_ID) private host: InjectionToken<string>
  ) {}

  ngOnInit(): void {
    if (platformServer) console.log(this.host);
  }

Angular version used is 9. Please someone shed some light on this issue. Thanks much in advance.

like image 272
Balan Gurumurthi Avatar asked Oct 27 '25 09:10

Balan Gurumurthi


1 Answers

It seems like you got this figured out already looking at the comments, but I'm wondering if the original issue in your code is that you are not actually using the HOST_ID injection token in your server's listener.

If you change your listener to something like this:

// All regular routes use the Universal engine
server.get('*', (req, res) => {
  res.render(indexHtml, {
    req,
    providers: [
      { provide: APP_BASE_HREF, useValue: req.baseUrl },
      { provide: HOST_ID, useValue: req.get('host') }, // sending host name in provider
    ],
  });
});

I think your problem will be fixed.

like image 156
Chris Gilardi Avatar answered Oct 29 '25 23:10

Chris Gilardi



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!