首页 > 解决方案 > 如何在 Spring Boot 中检索 url 并在 Angular 中使用它?

问题描述

在 Spring Boot 中,基本 url 可能localhost:8080或不同的。现在我想以角度使用它。我在网上看到很多示例只是用 Angular http 客户端调用代码对其进行硬编码。

但是基本 url 可以更改,例如端口号更改或环境从 dev 更改为 qa 或 production。所以我的问题是可能从弹簧启动动态暴露它并从角度检索它?

标签: javaangularspring-boot

解决方案


Your app should contain files at src/environments called environment.ts and environment.prod.ts. You can include a constant key value pair for your apiURL in this file like so:

export const environment = {
  production: false,
  apiUrl: 'localhost:8080'
}

And also include your production URL in the prod file. You can then use it in a file like so:

import { environment } from 'src/environment/environment.ts';
...
export class AppComponent implements OnInit {

  url: string;

  ngOnInit(): void {
     this.url = environment.apiUrl;
  }
}

推荐阅读