In a server directory I have a list of json files. I need to import each json filename into my angular 2 component in an array of string or other structure.
I tried to make an http.get to the web server using this service.
export class AnUtenteService {
getFiles() : Observable<string[]> {
return this.http.get(directory)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
But when in my component I call anutenteservice.getFiles() I get this error: Unexpected token < in JSON at position 0. This is my component
export class OrderslistComponent{
newsList;
errorMessage;
constructor(private anutenteservice: AnUtenteService, private http: Http)
{}
ngOnInit() {
this.anutenteservice.getFiles()
.subscribe(data => this.newsList = data,
error => this.errorMessage = <any>error);
}
}
I don't understand where is the mistake. What should I do?
Try to do this structure:
export class OrderslistComponent {
newsList;
errorMessage;
constructor(private anutenteservice: AnUtenteService) {
this.anutenteservice.getFiles.subscribe((data) => {
this.newsList = data;
}
);
}
ngOnInit() {
}
}
And add Http to your service class. Add this to your service class:
constructor(private http: Http) {
}
Update 1:
Try changing the type, here:
private extractData(res: Response) {
let body = res.text();
return body.data || { };
}
In case your response type is not a JSON.