如何使用Angular将.json配置导入environment.ts并使用api? [英] How to import .json config to environment.ts and consume api using Angular?

查看:394
本文介绍了如何使用Angular将.json配置导入environment.ts并使用api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想导入一个Json文件,该文件位于Assets文件夹中,其中有以下URL:

config.json:

{
    "url1": "https://jsonplaceholder.typicode.com/posts",

    "url2" : "https://reqres.in/api/users",

    "url3":"https://fakerestapi.azurewebsites.net/api/Authors"
}

因此,我不想对URL进行硬编码,而是要从Json文件导入,但是我不确定如何准确地做到这一点.

任何建议或方案将不胜感激,以下是我的问题:

1..如何将Json文件导入到environment.ts,从那里我将有一个使用api的服务

2..如果我导入文件,则prod和loc dev也必须相同

我想要的:

我有一个配置文件,该文件现在在资产文件夹中存储的.json文件中包含一些URL,而不是加载environments.prod.ts,我要加载我的Json文件配置并基于我要运行的文件我的申请

我做了什么:

下面是我放在资产文件夹中的Json文件

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

ConfigServiceService.ts 用于存储配置文件

public _config: Object;

    constructor(public http:Http) { }

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

此后,我创建一个 ServiceProviderService.ts 来调用服务文件

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();
 }

我无法获取Json数据,如果我将ServiceProviderService.ts文件中存在ngOnInit的逻辑放入构造函数中,那么我将变得未定义.

注意:在这里,如果有多个URL,则每个URL都会分发到各个单独的服务文件中,假设1个服务文件的base1 url和另一个文件的base2 url,我该如何实现

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

app.component.ts中的即时通讯未定义

解决方案

由于JSON文件中包含静态字符串,该文件已经保存在/assets文件夹中,并且不在服务器上,因此不需要使用http.get.
我们使用http协议仅从服务器/后端从JSON文件获取数据,而不从客户端文件夹获取数据.
您只需在需要的地方(甚至在environment.ts中)导入JSON文件,就像使用DTO一样. 将Typescript的ES6 import语句与JSON文件中的export结合使用.

资产/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"
})

然后在任何地方(组件,指令,服务,类,接口等...)

import { URLS } from 'assets/config.ts';

....

this.url1 = URLS.url1;

//或

let url1 = URL.url1;

现在this.url1可以在http.get内部的任何api调用中使用,例如:

 this.http.get(`${this.url1}`, { headers: this.getHeaders(token) });

 this.http.get(`${url1}`, { headers: this.getHeaders(token) }) // where url1 could be a variable or method parameter, etc...

就这样

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

解决方案

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

这篇关于如何使用Angular将.json配置导入environment.ts并使用api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆