如何在angular 4应用程序中存储api的根URL? [英] How to store the root url of api in angular 4 app?

查看:136
本文介绍了如何在angular 4应用程序中存储api的根URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了官方教程并为Apis提供了服务,但是Api的绝对URL在服务中进行了硬编码.

I followed the official tutorials and made services for the Apis but absolute url of the Api is hardcoded in services.

我想将Api的基本URL保留在某个位置,以便可以在调用之前将其附加到每个服务的URL路径中.我还需要在构建之前(或构建之后)更改Api的基本URL.

I want to keep the base url of Api somewhere so that i can append it to the url path in each service before call. i also need to change the base url of Api before building (or after building).

我试图将其放在sessionstorage中,但这是一个坏主意,因为任何人都可以更改它,并且我的应用程序将开始进入其他域.

i tried to put it in sessionstorage, but that is a bad idea as anyone can change it and my application will start hitting other domain.

所以我保持了它的硬编码,并在git上放置了一个后推钩子,以在构建后替换URL.但这更像是骇客,而不是解决方案.

so i kept it hard-coded and placed a post-push hook on the git to replace the url after build. but it is more like a hack than a solution.

我可以将文件放置在angular的根目录中,并将Api url设置为json格式.并将其包含在每个服务中,这样我就可以从git中排除该文件,并且每个队友和构建服务器都可以拥有自己的具有不同url的文件.

Can i place a file in the root directory of angular and put Api url in json format . And include it in each service so that i can exclude the file from git and each teammate and the build server can have their own file having different url.

推荐的做事方式是什么?

What should be the recommended way of doing it?

推荐答案

使用环境文件

如果您使用cli,则应使用环境文件.通过配置angular-cli.json文件,您可以管理所有可用环境并创建新的环境.例如,您可以通过使git忽略它来创建一个environment.dev.js文件并将其值存储在该文件中.您团队中的任何成员都可以拥有自定义文件.

If youre using the cli you should use the environment files. By configuring the angular-cli.json file you can manage all the available environments and create new ones. For example you could create an environment.dev.js file and store the values there, by making git ignore it any member in your team can have a customized one.

所说的环境文件将覆盖原始的environment.js

Said environment file will overwrite the original environment.js

请参见此答案 angular-cli for angular2如何加载环境变量

这篇关于如何在angular 4应用程序中存储api的根URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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