A Comprehensive Guide to Retrieving Base URL in Angular 5

Dec 08, 2025 · Programming · 17 views · 7.8

Keywords: Angular 5 | Base URL | Location Service | DOM API | Routing Configuration

Abstract: This article provides an in-depth exploration of various methods to obtain the base URL in Angular 5 applications, including the use of global DOM location object, Angular Location service, and related APIs. It offers detailed comparisons of different approaches, complete code examples, and best practice recommendations to help developers choose the most suitable solution based on specific requirements.

Introduction

In Angular application development, retrieving the current page's base URL is a common requirement, particularly when building dynamic links, handling routing, or interacting with backend APIs. The base URL typically refers to the combination of protocol, domain, and port number, such as extracting http://localhost:4200 from the complete URL http://localhost:4200/test/dashboard. This article systematically introduces multiple technical approaches to achieve this goal in Angular 5.

Using the Global DOM Location Object

The simplest and most direct approach is to utilize the browser's global location object. This is a DOM API that can be accessed directly in TypeScript code without any imports or injections.

// Direct usage in component methods
printBaseUrl(): void {
  // Get the complete base URL including protocol, domain, and port
  const baseUrl = location.origin;
  console.log(baseUrl); // Output: http://localhost:4200
  
  // Other useful location properties
  console.log(location.href);     // Complete URL
  console.log(location.pathname); // Path portion
}

The location.origin property returns the base URL of the current document, which is exactly what the original question requires. This method is suitable for most simple scenarios, particularly when the application is deployed at the root path and doesn't require complex routing configuration.

It's important to note that window.location and document.location are essentially references to the same object. In Angular's browser environment, these three can be used interchangeably, but location is the most concise notation.

Angular Location Service

For more complex application scenarios, especially those involving routing and different deployment paths, Angular provides the dedicated Location service. This service encapsulates underlying location operations and offers methods that better align with Angular paradigms.

import { Location, LocationStrategy } from '@angular/common';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-url-example',
  template: '...'
})
export class UrlExampleComponent implements OnInit {
  constructor(
    private location: Location,
    private locationStrategy: LocationStrategy
  ) {}

  ngOnInit(): void {
    // Use Location service to get path information
    const currentPath = this.location.path();
    console.log(currentPath); // Output: /test/dashboard
    
    // Construct external URL including base href
    const externalUrl = this.location.prepareExternalUrl('/');
    console.log(externalUrl); // Output may include base path
    
    // Directly get base href
    const baseHref = this.locationStrategy.getBaseHref();
    console.log(baseHref); // Output configured base path
  }
}

The advantage of the Location service lies in its ability to properly handle the application's base path configuration. When an application is deployed at a non-root path (e.g., /app/), the prepareExternalUrl() method automatically includes the base path, whereas directly using location.origin cannot handle this situation.

Injecting via DOCUMENT Token

Another approach involves using Angular's DOCUMENT token to inject the document object, then accessing its location property.

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

@Component({
  selector: 'app-document-example',
  template: '...'
})
export class DocumentExampleComponent {
  constructor(@Inject(DOCUMENT) private document: Document) {
    const origin = this.document.location.origin;
    console.log(origin); // Output base URL
  }
}

This method produces the same result as directly using the global location object but may offer advantages in specific scenarios such as server-side rendering or testing environments, as it provides better testability and environment abstraction through dependency injection.

Method Comparison and Selection Recommendations

Different methods suit different scenarios:

  1. Simple Scenarios: If the application is deployed at the root path and doesn't require complex routing handling, directly using location.origin is the simplest and most efficient choice.
  2. Angular Integration Scenarios: When the application uses Angular routing and may be deployed at non-root paths, the Location service should be prioritized as it integrates better with the Angular ecosystem.
  3. Special Environments: In scenarios requiring cross-platform compatibility or enhanced testability, injection via the DOCUMENT token may be the better option.

It's important to note that some older documentation may mention the need to configure the APP_BASE_HREF provider, but in modern Angular versions (including Angular 5), PathLocationStrategy automatically retrieves the base href from the DOM, eliminating the need for manual configuration.

Common Issues and Solutions

In practical development, the following issues may arise:

Issue 1: prepareExternalUrl() doesn't correctly include the base path.

Solution: Ensure that RouterModule is imported in the application, even if no routes are defined:

imports: [
  RouterModule.forRoot([]), // Empty route configuration
  // Other modules...
]

Issue 2: Different URL handling when using HashLocationStrategy.

Explanation: If the application uses hash routing strategy (URLs containing #), the behavior of prepareExternalUrl() and other location-related methods will differ. In such cases, special handling of URL construction logic is typically required.

Complete Example Code

The following comprehensive example demonstrates all major methods:

import { Component, Inject, OnInit } from '@angular/core';
import { DOCUMENT, Location, LocationStrategy } from '@angular/common';

@Component({
  selector: 'app-url-demo',
  template: `
    <div>
      <p>Base URL: {{ baseUrl }}</p>
      <button (click)="showAllMethods()">Show All Methods</button>
    </div>
  `
})
export class UrlDemoComponent implements OnInit {
  baseUrl: string;

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private location: Location,
    private locationStrategy: LocationStrategy
  ) {}

  ngOnInit(): void {
    // Initialize using the simplest method
    this.baseUrl = location.origin;
  }

  showAllMethods(): void {
    console.log('1. Global location:', location.origin);
    console.log('2. window.location:', window.location.origin);
    console.log('3. document.location:', document.location.origin);
    console.log('4. Injected document:', this.document.location.origin);
    console.log('5. Angular Location base path:', this.locationStrategy.getBaseHref());
    
    // Construct complete URL using prepareExternalUrl
    const fullUrl = this.location.prepareExternalUrl('/api/data');
    console.log('6. Constructed complete URL:', fullUrl);
  }
}

Conclusion

There are multiple methods to retrieve the base URL in Angular 5, each with its applicable scenarios. For most applications, location.origin provides the simplest and most direct solution. When closer Angular integration or handling of complex deployment scenarios is required, the Location service is the better choice. Developers should select the most appropriate method based on specific requirements, application architecture, and deployment environment, while being mindful of potential subtle differences between different Angular versions.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.