我将 SrpingBoot 应用程序作为 BE,将 AngularJS 作为 FE。 SpringBoot 位于端口 8553,Angular 位于 4203。因此,为了进行通信,我使用 proxy.conf.json,将所有请求从 4203 重定向到 8553,如下所示:
"/application": {
"target": "http://localhost:8553",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
我正在使用这样的代理启动角度应用程序:
ng serve app --port 4203 --proxy-config proxy.conf.json --disable-host-check true
一切正常。现在我想在不同的端口 8554 上运行另一个 SpringBoot 实例,并且我想使用相同的 Angular 实例并在 SpringBoot 实例之间切换。我想要一个下拉菜单,让用户选择两个不同的 SpringBoot 实例之一,并有角度地连接到该实例并将所有请求代理到该实例。
我尝试过两种不同的代理配置,但我不知道在运行时在它们之间切换什么。我不确定我当前的设置是否可以实现这一点。
如果可能的话,我还将尝试使用不同的环境文件并在运行时切换它们。 这更像是一个基础设施和架构问题,我不太擅长:D
假设您指的是 Angular 而不是 AngularJS,请按照以下步骤操作:
1。更新
proxy.conf.json
添加新的代理配置:
"/api1": {
"target": "http://localhost:8553",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
},
"/api2": {
"target": "http://localhost:8554",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
2。创建
ApiUrlService
使用属性
ApiUrlService
制作可注射服务apiUrl = 'api1'
。
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiUrlService {
apiUrl = 'api1'; // Default value
}
3. HTTP 拦截器
创建一个 HTTP 拦截器,将 '/api' 替换为
apiUrlService.apiUrl
。将 ApiUrlService
注入拦截器中。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiUrlService } from './api-url.service';
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
constructor(private apiUrlService: ApiUrlService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const apiReq = req.clone({ url: req.url.replace('/api', `/${this.apiUrlService.apiUrl}`) });
return next.handle(apiReq);
}
}
不要忘记在您的
AppModule
中注册拦截器:
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ApiInterceptor } from './api.interceptor';
@NgModule({
imports: [
HttpClientModule,
// other imports
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ApiInterceptor,
multi: true
}
],
// other module properties
})
export class AppModule { }
4。在运行时切换 API URL
要在运行时更改 API URL,请从表单修改
apiUrl
中的 ApiUrlService
值。
在组件中注入
ApiUrlService
:
constructor(public apiUrlService: ApiUrlService) {}
使用模板中的选择下拉列表在“/api1”和“/api2”之间切换(请记住导入 Angular
FormsModule
:
<select [(ngModel)]="apiUrlService.apiUrl">
<option value="api1">API 1 (Port 8553)</option>
<option value="api2">API 2 (Port 8554)</option>
</select>