3

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>
3
  • Did you try logging the returned json/parsed json to see what the data looks like? Maybe the issue is with your api running on localhost:54612 Commented Dec 27, 2016 at 17:32
  • I got this from the api: <ArrayOfPerson xmlns:i="w3.org/2001/XMLSchema-instance" xmlns="schemas.datacontract.org/2004/07/… i:nil="true" /><EMail i:nil="true" /><Geburtsdatum>0001-01-01T00:00:00</Geburtsdatum><IDPerson>1</IDPerson><Land i:nil="true" /><Mobile i:nil="true" /><Name i:nil="true" /><Ort i:nil="true" /><PLZ>0</PLZ><Passwort i:nil="true" /><Registrationsdatum>0001-01-01T00:00:00</Registrationsdatum><Telefon i:nil="true" /><Vorname i:nil="true" /></Person></ArrayOfPerson>. Is this what you mean? Commented Dec 27, 2016 at 17:36
  • 1
    This is not JSON. json starts with {and has key values such as "key":"value" then it finishes with } I guess this is why you cannot parse the json. Commented Dec 27, 2016 at 17:39

2 Answers 2

3

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 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, you are right. I just had to set my headers. What a facepalm :D
1

Try this snippet, in your getPersons()

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.