如何将.json配置导入environment.ts并使用angular消耗api [英] how to import .json config to environment.ts and consume api using angular

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

问题描述

我想导入一个Json文件,该文件位于我在以下网址的资源文件夹中:



config.json:

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

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

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

因此,我想从Json文件导入而不是硬编码URL,但我是不确定如何做到这一点。



任何建议或情况都会受到赞赏,以下是我的问题:



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



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



我想要什么



我有一个配置文件,其中包含一些URL在中。现在存储在资产文件夹中的json 文件,而不是加载 environments.prod .ts ,我想加载我的Json文件配置并基于我想要运行我的应用程序



我做了什么:



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

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

ConfigServiceService.ts 用于存储配置文件

  public _config:Object; 

构造函数(public http:Http){}

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

在此之后,我创建了一个 ServiceProviderService.ts 用于调用服务文件

  configData:any; 


构造函数(公共http:Http,公共配置:ConfigServiceService){

}

jsonData(){
调试器;
返回this.configData;
}

ngOnInit(){
debugger;
this.config.getData()。subscribe(res => {
console.log(res);
this.configData = res;
});


}

app.component.ts

  title ='sample'; 
构造函数(public serv:ServiceProviderService){
this.serv.jsonData();
}

我无法获取Json数据,如果我放逻辑如果我把它放在构造函数中,那么在ServiceProviderService.ts文件中有ngOnInit,那么我将得到未定义。



注意:此处如果有不止一次url然后每个url被分发到各个单独的服务文件假设base1 url为1个服务文件和base2 url为另一个文件我怎么能实现那个



解决方案

由于JSON文件中有静态字符串,因此已保存在/ assets folde中r并且它不在服务器上,您不需要使用 http.get

我们使用http协议从JSON文件中获取数据仅限服务器/后端,而不是客户端文件夹。

您只需要在任何需要的地方导入JSON文件(即使在environment.ts中),就像使用DTO一样。
在JSON文件中使用Typescript的ES6 import 语句与 export 结合使用。



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

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

 从'assets / config.ts'导入{URLS}; 

....

this.url1 = URLS.url1;

//或

  let url1 = URL.url1; 

现在 this.url1 可用于在 http.get 中的任何api调用,例如:

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

  this.http.get(`$ {url1}`,{headers:this.getHeaders(token)})//其中url1可以是变量或方法参数等等... 

这就是它


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

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

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