Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is best way to store API Urls and use in angular

Tags:

angular

I want to store all the API URLs in one place i.e in JSON file I want to use that JSON file through out my application.

i) what is the best location to keep the JSON file. ii) How to use the URLs in the Type script file

like image 367
Ram Kumar Avatar asked Jan 27 '20 09:01

Ram Kumar


1 Answers

i would store the base url in the environment.ts

export const environment = {
  production: false,
  baseUrl: 'http://example.com/api'  
};

and for the api URLs i would create an enum:

export enum ApiPaths {
   Auth = '/auth',
   Foo = '/foo',
   Bar = '/bar'
}

And then use it in the service:

import { environment } from '../environments/environment';
import { ApiPaths } from '../enums/api-paths';

@Injectable()
export class FooService {  

  baseUrl = environment.baseUrl;

  constructor(private httpClient: HttpClient) { }

  getAll() {
    let url = `${this.baseUrl}/${ApiPaths.Foo}/all`;
    return this.httpClient.get<JSON>(url);
  }
}
like image 200
Seryoga Avatar answered Sep 28 '22 02:09

Seryoga