[英]Angular 6 Unable to get data from external server API using proxy
I'm using local angular app and I get problem to get data from API on external server.我正在使用本地 angular 应用程序,但在从外部服务器上的 API 获取数据时遇到问题。 I tried to use proxy, so I create file proxyconfig.json and I included it in command line via
我尝试使用代理,所以我创建了文件proxyconfig.json并通过以下方式将它包含在命令行中
ng serve --proxy-config proxyconfig.json
And here is content:这是内容:
{
"/api/*": {
"target": "https://bittrex.com/api/v1.1/public/",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
I need to pass variables so I created service OrderBookService :我需要传递变量,所以我创建了服务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);
}
}
The problem is when I want to get this data and save it to variable in my component, path is not translating properly: it's sending request to http://localhost:4200/api/getorderbook?market=BTC-LTC&type=both instead of https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both :问题是当我想获取这些数据并将其保存到我的组件中的变量时,路径没有正确转换:它正在向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;
});
}
Anybody knows how to do it properly?有谁知道如何正确地做到这一点?
It's working fine when I put all path to proxconfig.json like this:当我像这样将所有路径放入 proxconfig.json 时,它工作正常:
{
"/api/*": {
"target": "https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
But I need to pass variables.但我需要传递变量。
You code你编码
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);
}
Just change url like只需更改网址即可
getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
const url = `/api/getorderbook?market=${currency1}-${currency2}&type=both`;
return this.httpClient.get<OrderBook[]>(url);
}
You don't need use http://localhost:4200 in you code.您不需要在代码中使用http://localhost:4200 。
And "pathRewrite": { "^/api": "" },
don't need too和
"pathRewrite": { "^/api": "" },
不需要太多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.