How do I set the baseUrl for Angular HttpClient?

后端 未结 6 1879
甜味超标
甜味超标 2021-01-30 06:21

I did not find a way in the documentation to set the base API URL for HTTP requests. Is it possible to do this with the Angular HttpClient?

6条回答
  •  生来不讨喜
    2021-01-30 07:11

    Excerpts from Visual studio 2017 asp.net core webapi angular sample application.

    include below lines in Main.ts

    export function getBaseUrl() {
      return document.getElementsByTagName('base')[0].href;
    }
    
    const providers = [
      { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
    ];
    

    in your component

      constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
        http.get(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
          this.forecasts = result;
        }, error => console.error(error));
      }
    

    my complete main.ts code looks like below

    import { enableProdMode } from '@angular/core';
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    import { AppModule } from './app/app.module';
    import { environment } from './environments/environment';
    
    export function getBaseUrl() {
      return document.getElementsByTagName('base')[0].href;
    }
    
    const providers = [
      { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
    ];
    
    if (environment.production) {
      enableProdMode();
    }
    
    platformBrowserDynamic()
      .bootstrapModule(AppModule)
      .catch(err => console.error(err));
    
    

    my component code looks like below

    import { Component, Inject } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Component({
      selector: 'fetch-weather',
      templateUrl: './weather.component.html',
      styleUrls: ['./weather.component.scss']
    })
    
    export class WeatherComponent {
      public forecasts: WeatherForecast[];
    
      constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
        http.get(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
          this.forecasts = result;
        }, error => console.error(error));
      }
    }
    
    interface WeatherForecast {
      dateFormatted: string;
      temperatureC: number;
      temperatureF: number;
      summary: string;
    }
    
    

提交回复
热议问题