Angular httpclient base url

For Angular HttpClient, you can set a base URL by providing a value for the “baseHref” property in the “index.html” file. The base URL is the URL path that precedes all relative URLs in your application.

If you want to set the base URL dynamically at runtime, you can make use of the “APP_BASE_HREF” token and the “PlatformLocation” service provided by Angular. Here’s an example:

// Import required modules
import { Component } from '@angular/core';
import { APP_BASE_HREF, PlatformLocation } from '@angular/common';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  template: `
    
    
{{ data }}
`, }) export class AppComponent { // Define HttpClient and base URL constructor(private http: HttpClient, private location: PlatformLocation) { // Set the base URL dynamically const baseUrl = (location as any).location.origin + '/api'; this.http = http; this.http.baseUrl = baseUrl; // This sets the base URL for all HttpClient requests } // Load data from the server using HttpClient loadData() { this.http.get('/products').subscribe((response) => { this.data = response; }); } }

In the above code, we import the required modules including HttpClient, APP_BASE_HREF, and PlatformLocation. Inside the AppComponent, we define the constructor and set the base URL dynamically using the PlatformLocation. The base URL will be the current origin (host and port) plus ‘/api’. The base URL is then set to the http.baseUrl property. Now, when we make an HttpClient request, we can use relative URLs and the base URL will be automatically prepended.

For example, when we call the loadData() method, it sends an HTTP GET request to ‘/products’. Since the base URL is set to ‘/api’, the actual request URL will be ‘http://localhost:4200/api/products‘. The response data is then assigned to the data property, which will be displayed in the <div> element.

Hope this helps! Let me know if you have any more questions.

Read more

Leave a comment