Search code examples
angulartypescripthttpget

How to set up BASE_URL in Angular Typescript?


I'm attempting to inject a BASE_URL into my TS files for all of my components. But I'm not sure where that gets created or how to set that up?

I'm trying to avoid writing out the full URL for each file to avoid having to change it depending on the device I run it on or if it is deployed. Right now I have it set to just be a string

"localhost:44347/*whatever*"

I want to be able to inject the localhost or base part of the URL rather than having to know what port I'm using beforehand. Is this possible and how would you do this?

EX: (This is ideally what I'd like to see)

 constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
  }

  getUrl(): Observable<any[]> {
    return this.http.get<any[]>(baseUrl)
  }

EDIT:

This is what I have tried to implement however I am still unable to use 'baseUrl' in my functions.

constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'API/weatherforecast').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }

 getUrl(): Observable<any[]> {
        return this.http.get<any[]>(baseUrl)
      }

Solution

  • You should be able to setup an InjectionToken somewhere in your project or library.

    Something like the following should work for you:

    export const BASE_URL: InjectionToken<string> = new InjectionToken<string>('baseURL');
    

    Then in your app module add a provider to the providers array for your token:

    { provide: BASE_URL, useValue: 'localhost:44347/*whatever*'}
    

    From there you should be able to inject as you have in your example above.