Ryter
Ryter

Reputation: 110

Angular2 REST API

I learn Angular2 and now i try to get my data from a rest service. My rest service works and i can get data from there.

But angular always give my this error message: JSON.parse: unexpected character at line 1 column 1 of the JSON data

This is my Service:

import { Injectable }     from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { Person } from '../_models/person';
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class PersonService {
    private headers: Headers;

    constructor(private http: Http)
    {
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

    getPersons(): Observable<Person[]> {
        return this.http.get('http://localhost:54612/api/Person')
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }

    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

This is the component for the view:

import { Component, OnInit } from '@angular/core';
import { Person } from '../_models/person';
import { PersonService } from '../_services/person.service';


@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html',
    providers: [ PersonService ]
})

export class LoginComponent implements OnInit {
    errorMessage: string;
    personen: Person[] = [];

    constructor(private personService: PersonService) { }

    ngOnInit() { this.getPersons(); }

    getPersons() {
        this.personService.getPersons()
            .subscribe(
            personen => this.personen = personen,
            error => this.errorMessage = <any>error);
    }
}

And this is my view:

<h1>Tour of Heroes</h1>
<h3>Heroes:</h3>
<ul>
    <li *ngFor="let person of personen">{{person.IDPerson}}</li>
</ul>
<p class="error" *ngIf="errorMessage">{{errorMessage}}</p>

Upvotes: 3

Views: 1357

Answers (2)

Praveen Rana
Praveen Rana

Reputation: 440

Try this snippet, in your getPersons()

return this.http.get('http://localhost:54612/api/Person',{headers: this.headers })
        .map((response:Response) => response.json())

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 208944

Your server is return XML. The reason is probably because it's the default when you don't explicitly set the Accept to something else. You have set it in the Headers to JSON, but you never add the headers to the request. You need to do

this.http.get('http://localhost:54612/api/Person', { headers: this.headers });

Upvotes: 3

Related Questions