Reputation: 2060
I am using Angular 4 and want to start using HttpClient
. However I get JSON parsing error and after alot of searching I have not been able to fix it yet.
Old method
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);
}
Converting to 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)
);
}
On converting to HttpClient I get the following error message
Backend Controller code:
[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);
}
}
I have been looking around SO and other sources. This SO post explains HttpClient but this still does not resolve my error. Any help is highly appreciated. Thanks
Upvotes: 1
Views: 576
Reputation: 155065
A recent breaking-change in Angular's HttpClient
means that deserializing a JSON body with HTTP 200 OK
responses with empty content now trigger this "unexpected end of data at ... of the JSON data" error because it should be using HTTP 204 No Content
. See here: https://github.com/angular/angular/issues/20879
There are 3 possible fixes:
{ responseType: "text" }
).Upvotes: 2