Estoy iniciando en esto de Angular 2 y lo que quiero es interrogar una API rest con Angular 2 Typescript, usando Angular-cli, por ello creé un servicio un modelo y un componente para interrogar a la api.
Componente
import { Component, OnInit } from '@angular/core';
import {LiguesServices} from '../services/ligues.services'
import { ligueModel } from '../models/ligueModel'
@Component({
selector:'ligues',
templateUrl: '../templates/ligues.component.html',
moduleId: module.id
})
export class liguesComponent implements OnInit{
public liguesList : Array<ligueModel> = [];
constructor(private service:LiguesServices){}
ngOnInit(){
this.service.getLigues().subscribe(
data => {this.liguesList = data;},
error => {alert('Error');})
}
}
HTML
<h2>Ligues de Football</h2>
<p>Liste de ligues</p>
<div class="row">
<div class="col s12 m6" *ngFor="let item of liguesList ">
<div class="card">
<div class="card-image">
<img src="../images/football-header.jpg">
<span class="card-title">{{item.caption}}</span>
<a class="btn-floating halfway-fab waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
<div class="card-content">
<p>{{item.league}}, {{item.year}}</p>
</div>
</div>
</div>
</div>
<p>{{liguesList}}</p>
Servicio
import { Injectable} from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/Operator/map';
import { ligueModel } from '../models/ligueModel'
@Injectable()
export class LiguesServices{
constructor(public http: Http){}
getLigues():Observable<ligueModel[]>{
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');
return this.http.get('http://api.football-data.org/v1/competitions/?season=2017', {headers: headers})
.map((res:any) => res.json() as ligueModel[]);
}
}
Modelo
export class ligueModel{
public ligueID: number;
public captation: string;
public league: string;
public year: string;
public currentMatchDay:number;
public numberOfMatchday: number;
public numberofTeams: number;
public numberofGames: number;
public lastUpdated: string;
}
pero tengo errores al momento de ejecutar Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.football-data.org/v1/competitions/?season=2017. (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
Estoy usando Mozilla como navegador de prueba
accept
, oX-Requested-With
) en donde sólo aceptasContent-Type
. Además, al ser cross origin probablemente envía una petición de tipoOPTIONS
como preflight y tú sólo estás permitiendo las peticionesGET
.