angular - 如何根据 url angular 2 创建对后端的动态请求
问题描述
我有一个 Angular 应用程序(它是生产版本)。应用程序可在两个链接(http://blabla.com,http://test.com)。现在:对于您打开应用程序的任何 url,前端都会通过 url (test.com/api) 发送后端请求,因为它在环境中是硬编码的。我应该根据我拥有的 URL 向后端发出请求。例如,URL 是 blablabla.com,我必须创建一个请求来后端 blablabla/api
private apiUrl = environment.apiUrl.replace(/[/]+$/, '');
private getUrl(url: string): string
return `${this.apiUrl}/${url}`;
}
public get<TResponse extends ApiResponse<any>>(url: string, options?: ApiRequestOptions): Observable<any> {
let requestUrl = this.getUrl(url);
let httpOptions = this.getHttpOptions(options);
if (options && options.observe) {
return this.httpClient.get<TResponse>(requestUrl, {
observe: options.observe,
...httpOptions,
});
} else {
return this.httpClient.get<TResponse>(requestUrl, httpOptions);
}
}
export const environment = {
production: true,
apiUrl: 'https://test.com/api/v1/',
};
解决方案
如果您有服务前。getSomeDataService,你可以像这样注入你的组件并在那里使用。getSomeData.service.ts:
import {HttpClient, HttpHeaders} from '@angular/common/http';
...
// headers if they are needed
getDataBack(url: string) {
return this.http.get(url);
}
sometig.component.ts:
...
import {GetSomeDataService} from '../services/getSomeData.service';
...
// inject into constructor
constructor(private getSomeService: GetSomeDataService){}
// after that in ngOnInit or elsewhere
ngOnInit() {
url = location.host+'/api'; // or location host
this.getSomeService(url)
.subscribe(response => console.log());
}
更新
所以你有以下内容:
// hardcoded url which located in src/environment.prod.ts not necessary
//private apiUrl = environment.apiUrl.replace(/[/]+$/, '');
private getUrl(url: string): string
//return `${this.apiUrl}/${url}`;
//here change the logic..
return `${location.host}/${url}`;
}
推荐阅读
- c# - .NET 5 Core Entity Framework Controller w/OData Return Child Object with a Child Object
- sql - 如何在 BigQuery 中取消透视结构?
- c++ - C++ 入门(第 5 版);第 19 章 - 算法:std::lower_bound
- visual-studio-code - 如何让 Visual Studio Code 自动滚动调试控制台?
- javascript - HTML 输入元素大小为 0
- python - Discord bot 不响应命令(python)
- r - r 相关矩阵长格式
- c# - C# ReportViewer 未指定报表定义的来源
- discord.js - 当我尝试获取我的机器人状态并执行节点时,“未定义客户端”
- spring-boot - Springboot REST API 全局扩展处理程序