I'm starting this in Angular 2 and what I want is to interrogate a rest API with Angular 2 Typescript, using Angular-cli, so I created a service a model and a component to interrogate the api.
Component
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>
Service
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[]);
}
}
Model
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;
}
but I have errors when executing Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at link . (Reason: missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
I'm using Mozilla as a test browser