角度允许定义
environment
. 以下是我所做的:
-
在你的
src
environments
文件夹。
-
创建以下文件并根据需要调整内容(应该已经有一个名为
environment.ts
好了,我稍后再谈。目前:
environment.dev.ts
export const environment = {
production: true,
apiURL: "http://127.0.0.1:8000/my-api"
};
environment.prod.ts
export const environment = {
production: true,
apiURL: "https://api.yoururl.com/"
};
-
修改您的
angular.json
:
...
"configurations": {
...
"production": {
"outputPath": "dist-prod/",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
}
"dev": {
"outputPath": "dist-dev/",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev.ts"
}
],
}
...
为了
ng serve
环境.ts
文件,所以内容应该与
.
通过调用以下命令,可以使用此设置创建生成:
ng build --configuration dev
ng build --configuration prod
-
在您的服务/组件中使用:
import { environment } from 'your/path/environments/environment';
@Injectable()
export class EchoService {
constructor(private httpClient: HttpClient) {}
public makeCall(): Observable<any> {
return this.httpClient.get<any>(
environment.apiURL + 'your/endpoint/
);
}
}
现在,根据配置,
environment.apiURL
可能是
127.0.0.1:8000
https://....
.
万一我漏了什么,你可以看看
here
.