Can't use fetch to set an arrayList in typescript


#1

Hi, I can’t set my vehicule object in my vehiculeList using fetch method.

import { Injectable } from “@angular/core”;
import { Http, Headers } from “@angular/http”;
import { Observable } from “rxjs/Rx”;
import “rxjs/add/operator/map”;

import { Config } from “…/config”;
import { Vehicule } from “./vehicule”;

@Injectable()
export class VehiculeListService {
vehiculeList : Array = [];

constructor(private http: Http) { }

load() { // this function is call in a component.ts
fetch(Config.apiUrl + “index.php?type=vehicules”).then(response => {
return response.json();
}).then(response => {
var vehiculeList;
for (var item in response) {
var vehicule = new Vehicule();
vehicule.id = response[item].id;
vehicule.registration = response[item].registration;
this.vehiculeList.push(vehicule);
console.dir(this.vehiculeList); // Here vehiculeList is full of vehicule
}return vehiculeList;
});
console.dir(this.vehiculeList); // Here vehiculeList is empty.
}

handleErrors(error: Response) {
console.log(JSON.stringify(error.json()));
return Observable.throw(error);
}

}

I hope that somebody will help me! :wink:
Thanks, Francois