英文:
How to make dynamic API calls in Angular project
问题
以下是代码的中文翻译部分:
我正在使用以下的Typescript函数来获取API数据:
export class BomService {
constructor(private http: HttpClient) { }
GetAllBomList(): Observable<IBom[]> {
return this.http.get<IBom[]>('http:192.168.10.1:5000/api/bom/getallboms');
}
}
当我在自己的计算机上使用时,我可以完全加载数据,但是当我尝试通过互联网访问时,UI可以加载,但数据无法获取。原因是HTTP地址。API和UI都托管在同一台使用IIS的服务器上。我该如何解决这个问题?
英文:
I'm using the following Typescript function to get access to API data:
export class BomService {
constructor(private http: HttpClient) { }
GetAllBomList(): Observable<IBom[]> {
return this.http.get<IBom[]>('http:192.168.10.1:5000/api/bom/getallboms');
}
}
When I use my own computer I can load data completely but when I'm trying to get access through Internet, the UI is loaded but the data cannot be fetched. The reason is Http address. Both the API and the UI are hosted in the same server using IIS. How can I solve this problem?
答案1
得分: 1
Angular 15及以下版本有一个environments
文件夹。Angular 15及以上版本,您需要首先在项目中运行ng g environments
命令。然后,您会看到这些文件/文件夹(文件名可能不同)。
这些文件看起来像这样:
environment.development
export const environment = {
serverPath: 'http://localhost:3000',
};
environment(生产环境)
export const environment = {
serverPath: 'http://123.123.123.123:3000', // 服务器路径
};
其余的魔法由Angular为您完成。因此,在您的服务/组件或任何需要的地方,您需要像这样导入该文件:
Service
import { environment } from 'src/environments/environment';
...
GetAllBomList(): Observable<IBom[]> {
return this.http.get<IBom[]>(environment.serverPath + '/api/bom/getallboms');
}
阅读有关环境的更多信息在这里。简而言之,在angular.json
文件中,您将找到环境文件。一个用于dev
(开发)和一个用于production
(生产)。如果您运行ng build
,Angular将使用production
文件替换dev
文件。您无需执行其他操作。
英文:
Angular < 15 has an environments folder. Angular 15+ you need first call ng g environments
inside your project. Then you see this folders/files (names can be different of the files)
The files looks like this:
environment.development
export const environment = {
serverPath: 'http://localhost:3000',
};
environment (production)
export const environment = {
serverPath: 'http://123.123.123.123:3000', // Server path
};
The rest of the magic do Angular for you. So in your service/component or what you want you need to import the file like this:
Service
import { environment } from 'src/environments/environment';
...
GetAllBomList(): Observable<IBom[]> {
return this.http.get<IBom[]>(environment.serverPath + '/api/bom/getallboms');
}
Read all about environments here. But in short: In the angular.json
file you will find the environments files. One for dev
and one for production
. If you run ng build
Angular will replace the dev
file with the production
file. You need to do nothing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论