I'm trying to retrieve data from an api using angular.
This is a sample of the data i get when I use Postman(Chrome extension) GET
[{"cuisine": "Bakery", "borough": "Bronx", "name": "Morris Park Bake Shop", "restaurant_id": "30075445", "grades": [{"date": {"$date": 1393804800000}, "grade": "A", "score": 2}, {"date": {"$date": 1378857600000}, "grade": "A", "score": 6}, {"date": {"$date": 1358985600000}, "grade": "A", "score": 10}, {"date": {"$date": 1322006400000}, "grade": "A", "score": 9}, {"date": {"$date": 1299715200000}, "grade": "B", "score": 14}], "address": {"building": "1007", "street": "Morris Park Ave", "zipcode": "10462", "coord": [-73.856077, 40.848447]}, "_id": {"$oid": "58fffbef0bc7de46499ad5c6"}}]
places.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Place } from './place';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class PlacesService {
constructor(private http: Http) { }
private baseUrl: 'http://example.com/api'
getPlaces(): Observable<Place[]> {
return this.http.get(this.baseUrl)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'))
}
}
places.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PlacesService } from './places.service';
import { Place } from './place';
import { AuthService } from '../providers/auth.service';
@Component({
selector: 'places',
templateUrl: './places.component.html',
styleUrls: ['./places.component.css']
})
export class PlacesComponent implements OnInit {
constructor(
public authService: AuthService,
private router: Router,
private placesService: PlacesService
)
{ }
places: Place[];
loadPlaces() {
this.placesService.getPlaces()
.subscribe(
places => this.places = places,
err => {
console.log(err);
});
}
ngOnInit() {
console.log(this.loadPlaces());
this.loadPlaces()
}
}
place.ts
export class Place {
constructor(
public restaurant_id: number,
public name: string
) { }
}
Sorry for the long question but I figured that it would help if I posted everything.
This is error:
SyntaxError: Unexpected token < in JSON at position 0
at Object.parse (<anonymous>)
at Response.Body.json (body.js:24)
at CatchSubscriber.selector (places.service.ts:18)
at CatchSubscriber.error (catch.js:104)
at MapSubscriber.Subscriber._error (Subscriber.js:128)
at MapSubscriber.Subscriber.error (Subscriber.js:102)
at XMLHttpRequest.onLoad (xhr_backend.js:82)
at ZoneDelegate.invokeTask (zone.js:367)
at Object.onInvokeTask (ng_zone.js:264)
at ZoneDelegate.invokeTask (zone.js:366)
at Zone.runTask (zone.js:166)
at XMLHttpRequest.ZoneTask.invoke (zone.js:420)