How to import .json config to environment.ts and consume api using Angular?
Since you have static strings in a JSON file, which is already saved in /assets folder and it's not on the server, you don't need to use http.get
.
We use http protocol to get data from JSON files from the server/backend only, not from the client side folders.
You just need to import the JSON file wherever you need (even in environment.ts), as you would do with DTOs.
Use Typescript's ES6 import
statement combined with export
in the JSON file.
assets/config.ts
export const URLS = Object({
"url1": "https://jsonplaceholder.typicode.com/posts",
"url2" : "https://reqres.in/api/users",
"url3":"https://fakerestapi.azurewebsites.net/api/Authors"
})
Then anywhere (components, directives, services, classes, interfaces, etc ...)
import { URLS } from 'assets/config.ts';
....
this.url1 = URLS.url1;
//or
let url1 = URL.url1;
Now this.url1
can be used in any api call inside http.get
, for example:
this.http.get(`${this.url1}`, { headers: this.getHeaders(token) });
or
this.http.get(`${url1}`, { headers: this.getHeaders(token) }) // where url1 could be a variable or method parameter, etc...
That's it