【问题标题】:Angular2 REST APIAngular2 REST API
【发布时间】:2016-12-27 17:28:28
【问题描述】:

我学习了 Angular2,现在我尝试从休息服务中获取我的数据。我的休息服务有效,我可以从那里获取数据。

但是 Angular 总是给我这个错误信息:JSON.parse: unexpected character at line 1 column 1 of the JSON data

这是我的服务:

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);
    }
}

这是视图的组件:

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);
    }
}

这是我的观点:

<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>

【问题讨论】:

  • 您是否尝试记录返回的 json/解析的 json 以查看数据的样子?也许问题在于您的 api 在 localhost:54612 上运行
  • 我从 api 得到这个:w3.org/2001/XMLSchema-instance" xmlns="schemas.datacontract.org/2004/07/… i:nil="true" />0001-01-01T00:00:00100001-01-01T00:00: 00。这是你的意思吗?
  • 这不是 JSON。 json 以{ 开头并具有诸如"key":"value" 之类的键值,然后以} 结尾我想这就是您无法解析json 的原因。

标签: rest http angular get


【解决方案1】:

您的服务器返回 XML。原因可能是因为当您没有将 Accept 显式设置为其他值时,它是默认值。您已在 Headers 中将其设置为 JSON,但您从未将标头添加到请求中。你需要做的

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

【讨论】:

  • 谢谢,你是对的。我只需要设置我的标题。真是个面子:D
【解决方案2】:

在你的 getPersons() 中试试这个 sn-p

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2016-11-08
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多