Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import .json config to environment.ts and consume api using Angular?

I want to import a Json file which is in assets folder where I have below urls:

config.json:

{
    "url1": "https://jsonplaceholder.typicode.com/posts",
    
    "url2" : "https://reqres.in/api/users",
    
    "url3":"https://fakerestapi.azurewebsites.net/api/Authors"
}

So instead of hard coding the URL, I want to import from Json file, but I am not sure how to do that exactly.

Any suggestions or scenarios would be appreciated, below are my issues:

1. How to import Json file to environment.ts and from there I will have a service which consumes the api

2. If I import the file, it needs to be the same for prod and loc dev also

what I want :

I have a config file where it contains some URL's in .json file stored in asset folder now instead of loading environments.prod or .ts, I want to load my Json file config and basing on that I want to run my application

what I did:

Below is my Json file which I placed in asset folder

{
    "baseUrl": "https://jsonplaceholder.typicode.com/",
    "baseUrl2": "https://reqres.in/api/users"
}

ConfigServiceService.ts for storing config file

public _config: Object;

    constructor(public http:Http) { }
    
    getData(){
       debugger;
       return this.http.get("./assets/config.json").pipe(map(res =>  res.json()));
    }

After this, I create a ServiceProviderService.ts for calling the service file

configData:any;


   constructor(public http:Http,public config:ConfigServiceService) {
    
   }
    
   jsonData(){
       debugger;
       return this.configData;
   }
    
   ngOnInit(){
      debugger;
      this.config.getData().subscribe(res =>{
         console.log(res);
         this.configData = res;
      });
    
    
   }

app.component.ts

 title = 'sample';
 constructor(public serv :ServiceProviderService){
      this.serv.jsonData();
 }

I am not able to get the Json data and if I am putting the logic which is there is ngOnInit in ServiceProviderService.ts file if I put it in constructor then I am getting undefined.

Note : here if there are more than once url then each url is distributed to various seperate service file suppose base1 url for 1 service file ans base2 url for another file how can I achieve that

https://stackblitz.com/edit/read-local-json-file-5zashx

in app.component.ts im getting undefined

enter image description here

like image 211
Dexter Avatar asked Mar 21 '19 16:03

Dexter


3 Answers

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

like image 173
Vega Avatar answered Nov 06 '22 01:11

Vega


You can create a service to read Json file using HttpClient

export class SettingService  {

  constructor(private http: HttpClient) {

  }

  public getJSON(file): Observable<any> {
      return this.http.get("./assets/configs/" + file + ".json");
  }
  public getSetting(){
      // use setting here
  }
}

You should save 3 url to session storage or localstorage instead of enviroment.ts incase you refresh page

Refer Angular: Is it possible to read a json file after building

like image 1
Hien Nguyen Avatar answered Nov 06 '22 01:11

Hien Nguyen


You can use required 🤔 to read a json file from assets

/assets/urls.json 📄

{
  "urls": {
    "dev": "dev.com",
    "prod": "prod.com"
  }
}

env.ts

const { urls } = require("../assets/urls.json");

export const environment: IEnv = {
  production: false,
  baseUrl: urls.dev
};

env.prod.ts

const { urls } = require("../assets/urls.json");
export const environment: IEnv = {
  production: true,
  baseUrl: urls.prod
};

🚨 you need to install npm i @types/node and update tsconfig.app.json like this

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}
like image 1
Muhammed Albarmavi Avatar answered Nov 06 '22 03:11

Muhammed Albarmavi