我正在尝试使用角对足球数据api进行成功的api调用。以下是文档:http://www.football-data.org/documentation
使用文档中的示例代码,我成功地使用jQuery获得JSON数据,如下所示:
$.ajax({
headers: { 'X-Auth-Token': 'YOUR_API_TOKEN' },
url: 'http://api.football-data.org/v1/fixtures?timeFrame=n1',
dataType: 'json',
type: 'GET',
}).done(function(response) {
// do something with the response, e.g. isolate the id of a linked resource
var regex = /.*?(\d+)$/; // the ? makes the first part non-greedy
var res = regex.exec(response.fixtures[0]._links.awayTeam.href);
var teamId = res[1];
console.log(teamId);
});但是相对于角度来说,我不知道如何在这种环境下做同样的事情。通过一些教程,我已经设置了一个service,它使用HTTP来map从url到JSON的响应,如下所示:
export class FootballService {
private _url: string = "http://api.football-data.org/v1/competitions/426/leagueTable";
constructor(private _http: Http) { }
getLeagueTable(){
return this._http.get(this._url)
.map((res: Response) => res.json());
}
}我将这个服务导入到我的组件上,如下所示:
export class ApiComponent implements OnInit {
table = [];
constructor(private _footyService: FootballService) { }
ngOnInit() {
this._footyService.getLeagueTable()
.subscribe(res => this.table = res);
}
}但是,我的代码中显然存在一些我无法识别的问题,因为我无法通过它获得任何有效的JSON。如果有人能帮我的忙我会很感激的。
发布于 2017-05-01 03:12:25
看看http客户端的角度教程。特别是headers部分:https://angular.io/docs/ts/latest/guide/server-communication.html#!#headers
您需要按以下方式使用http服务:
首先看看Http:https://v2.angular.io/docs/ts/latest/api/http/index/Http-class.html的api
get(url: string, options?: RequestOptionsArgs) : Observable<Response>
RequestOptionsArgs api:https://v2.angular.io/docs/ts/latest/api/http/index/RequestOptionsArgs-interface.html
interface RequestOptionsArgs {
url : string
method : string|RequestMethod
search : string|URLSearchParams
headers : Headers
body : any
withCredentials : boolean
responseType : ResponseContentType
}所以你可以使用:
let headers = new Headers({ 'X-Auth-Token': 'YOUR_API_TOKEN' });
let options = new RequestOptions({ headers: headers });
this.http.get('URL HERE', options).subscribe(...)发布于 2017-05-01 03:00:53
您需要从服务提供者获得“YOUR_API_TOKEN”并将其传递给标头。
headers: { 'X-Auth-Token': 'YOUR_API_TOKEN' }喜欢
this._http.get(this._url,
new RequestOptions({headers: {'X-Auth-Token': 'YOUR_API_TOKEN'}}));发布于 2019-08-01 12:54:58
让我们深入研究01-08-2019解决方案:
进口:
import {Http,Headers} from '@angular/http';然后您需要声明类型为headers的对象,如下所示:
headers = new Headers();
url1;之后,您必须将其附加到构造函数中的headers变量中:
this.headers.append('X-RapidAPI-Key', 'c7ea217786msh32_Rest of your token_83fjsn7f8b8fe644f0');
this.url1 = 'https://api-football-v1.p.rapidapi.com/v2/leagueTable/2';最后一步是像下面这样填充get 方法:
getStandings() {
// tslint:disable-next-line: deprecation
return this.http.get(this.url1 , {headers: this.headers}).pipe(
map(res => res.json())
);
}这就是使您的令牌正常工作所需的全部条件。
https://stackoverflow.com/questions/43713600
复制相似问题