我正在使用本地角度应用程序,但在从外部服务器上的API获取数据时遇到问题。我尝试使用代理,所以我创建了文件 proxyconfig.json ,并通过
将其包含在命令行中ng serve --proxy-config proxyconfig.json
这里是内容:
{
"/api/*": {
"target": "https://bittrex.com/api/v1.1/public/",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
我需要传递变量,所以我创建了服务 OrderBookService :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { OrderBook } from './order-book.model';
@Injectable({
providedIn: 'root',
})
export class OrderBookService {
constructor(private httpClient: HttpClient) {
}
getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
const url = `http://localhost:4200/api/getorderbook?market=${currency1}-${currency2}&type=both`;
return this.httpClient.get<OrderBook[]>(url);
}
}
问题是当我想获取此数据并将其保存到组件中的变量时,路径未正确转换:它将请求发送到 http://localhost:4200/api/getorderbook?market=BTC-LTC&type=both 而不是 https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both :
private getTransfers(): void {
const currency1 = 'BTC';
const currency2 = 'LTC';
this.orderBookService.getOrderBookBittrex(currency1, currency2)
.subscribe(orders => {
this.orderBook = orders;
});
}
有人知道该怎么做吗?
当我将所有路径都放入proxconfig.json时,它工作正常:
{
"/api/*": {
"target": "https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
但是我需要传递变量。
答案 0 :(得分:1)
您编码
getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
const url = `http://localhost:4200/api/getorderbook?market=${currency1}-${currency2}&type=both`;
return this.httpClient.get<OrderBook[]>(url);
}
只需更改网址,如
getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
const url = `/api/getorderbook?market=${currency1}-${currency2}&type=both`;
return this.httpClient.get<OrderBook[]>(url);
}
您不需要在代码中使用http://localhost:4200。
还有"pathRewrite": {
"^/api": ""
},
也不需要