Get domain name for service in Angular2

Viewed 113588

I need to make request to same server, REST API on another port.

How can I do this without hardcoding full name in service URLs?

9 Answers

You can use window, as others have stated, and to make it injectable, from ng6 and forward, you need an injection token.

Declare the token like this:

export const WINDOW = new InjectionToken('window',
    { providedIn: 'root', factory: () => window }
);

Then use it in the class constructor:

class Foo {
  constructor(@Inject(WINDOW) private window: Window) { }
}

As Window is an interface in TypeScript, if you don't do the injection like that, when you build the project for production you will get an error: Can't resolve all parameters for <ClassName>. And later another one: ERROR in : Error: Internal error: unknown identifier undefined.

To understand injection better, read the angular docs for DI: https://angular.io/guide/dependency-injection

I'm using plain javascript and URL native api for URL parsing:

declare var window: any; // Needed on Angular 8+
const parsedUrl = new URL(window.location.href);
const baseUrl = parsedUrl.origin;
console.log(baseUrl); // this will print http://example.com or http://localhost:4200

I test this on Angular 7 and it worked correctly

declare var window: any;

console.log (window.location.host); //result lrlucas.github.io > domain github pages

with window.location.host I get the full domain

Note: Declare the window variable before @Component

Just inject Document. Angular has a default implementation for Document. Document has a property called defaultView that has all the goodies like window.

import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class HostnameService
{

  constructor(
    @Inject(DOCUMENT) private document: Document
  ) { }

  getHostname(): string
  {
    // Remember to use this.document as unscoped document also exists but is not mockable.
    return this.document.defaultView.window.location.hostname;

    // Or use the location on document.
    return this.document.location.hostname;

  }
}

There is no setup required elsewhere.

Related