什么是存储 API Urls 并在 angular 中使用的最佳方式 [英] what is best way to store API Urls and use in angular

查看:24
本文介绍了什么是存储 API Urls 并在 angular 中使用的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将所有 API URL 存储在一个地方,即在 JSON 文件中我想在整个应用程序中使用该 JSON 文件.

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) 保存 JSON 文件的最佳位置是什么.ii) 如何使用 Type 脚本文件中的 URL

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

推荐答案

我会将基本 url 存储在 environment.ts 中

i would store the base url in the environment.ts

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

对于 api URL,我会创建一个枚举:

and for the api URLs i would create an enum:

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

然后在服务中使用:

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

这篇关于什么是存储 API Urls 并在 angular 中使用的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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