我正在使用Angular 4,并且想开始使用HttpClient
。但是我收到JSON解析错误,经过大量搜索后,我仍无法修复它。
旧方法
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { _throw } from 'rxjs/observable/throw';
import { AppConfig } from '../config/app.config';
import { AuthenticateService } from '../security/shared/authenticate.service';
import { IFlower } from './flower.model';
addFlower(Flower: IFlower): Observable<any> {
this._auth.checkToken();
const headers = new Headers();
this.createAuthorizationHeader(headers, this._auth.token);
headers.append('Content-Type', 'application/json');
this.options = new RequestOptions({ headers: headers });
return this._http.post(this.apiUrl + 'flower/insert', JSON.stringify(Flower),
this.options).map((res: Response) => <any>res).catch(this.handleError);
}
转换为HttpClient
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { _throw } from 'rxjs/observable/throw';
import { AppConfig } from '../config/app.config';
import { AuthenticateService } from '../security/shared/authenticate.service';
import { IFlower } from './flower.model';
addFlower(Flower: IFlower): Observable<any> {
this._auth.checkToken();
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer ' + this._auth.token,
'Content-Type': 'application/json'
})
};
return this._http.post<any[]>(this.apiUrl + 'flower/insert', JSON.stringify(Flower), httpOptions)
.pipe(
catchError(this.handleError)
);
}
转换为HttpClient时,出现以下错误消息
https://core.rasa.com/patterns.html?highlight=fallback%20policy#fallback-default-actions
后端控制器代码:
[HttpPost]
[Route("insert")]
public HttpResponseMessage AddFlower(Flower flower)
{
try
{
_flowerervice.AddFlower(flower, token));
return Request.CreateResponse(HttpStatusCode.Created);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Forbidden"));
}
catch (Exception exception)
{
throw ExceptionMessageUtility.HttpResponse(Request, exception);
}
}
答案 0 :(得分:2)
Angular的HttpClient
中最近发生的重大变化意味着,用HTTP 200 OK
响应反序列化JSON正文的内容为空,现在会触发此“在JSON数据的...处意外的数据结尾”错误,因为应该使用HTTP 204 No Content
。看到这里:https://github.com/angular/angular/issues/20879
有3种可能的解决方法:
{ responseType: "text" }
)。