angular - 如何为角度前端本地的后端服务器提供服务?
问题描述
我有一个在 apache 服务器上运行的 Angular 应用程序http://localhost
。我有一个后端烧瓶服务器在端口 5200 ( )
上的同一台机器上运行。http://localhost:5200
我可以从服务器通过前端访问后端,但是当我从另一台机器上尝试时,前端显然将客户端引用到他自己的没有运行后端的机器上。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of } from 'rxjs';
@Injectable()
export class DataService {
dataUrl = 'http://localhost:5002/api'
constructor(private http: HttpClient) { }
getData(): Observable<DataItem> {
return this.http.get<DataItem>(this.dataUrl)
}
}
有没有办法让我做这样的事情?
dataUrl = 'http://${SameIpAsFrontEnd}:5002/api'
解决方案
出于这些目的,有环境文件。您可以使用它们来引用不同的后端服务器,在您的情况下localhost
,“ . You can use the standard development and prod environment file or you can create your own ones.
If you use
ng serve”将自动在开发模式下运行,这将提供开发环境文件。但您也可以提供任意文件(例如):
ng serve -e prod
环境文件位于目录中environments
。假设文件如下所示:
export const environment = {
production: false,
server: "localhost"
};
environment.server
例如,您可以在 REST 服务中访问基本 URL 。在标准角度项目中,会有environment.prod.ts
和environment.ts
。ng serve
没有-e
将采取environment.ts
。如果您使用-e prod
它,它将采取另一个。当然,您也可以像这样定义环境文件:( environment.stub.ts
) ng serve -e stub
。
在您的示例中,您可以使用:
dataUrl = 'http://' + environment.server + ':5002/api'
要使用特定的 env 文件构建应用程序,请使用:
ng build --prod --env=prod
推荐阅读
- typescript - 如何在打字稿的类中声明枚举?
- python - 如何在apache默认conf文件中添加多个python-path
- node.js - 如何识别和处理单个话语中的多个意图
- azure - 创建新应用程序
- regex - 我需要用 sed 转义哪些字符才能使这个正则表达式工作
- angular - Google App Engine 的部署问题
- java - Eclipse IDE 错误,cmd 显示“Java.lang.classnotfoundexception:version”
- angular - Karma/Jasmine 强制导入无关组件
- c++ - 将 Python 数据读入 C++ 代码
- angular - Angular 6:错误:找不到“object”类型的不同支持对象“[object Object]”。NgFor 只支持绑定到 Array 等 Iterables