Angular 2 / Web Api - json parsing error error de sintaxis inesperado final de entrada


Tengo un controlador Web API que se ve así:

    [HttpPost]
    public IHttpActionResult Test()
    {
        return Ok();
    }

Esta es la sintaxis correcta, Sin embargo, cuando intento llamar a esto desde un servicio en Angular 2, recibo el mensaje de error: "error de sintaxis de análisis json error inesperado final de entrada."Para resolver este problema, tengo que poner un valor en el ActionResult como

return Ok(1)

¿Me falta alguna configuración? Mi llamada de servicio Angular 2 se ve así:

return this.http.post(API/Controller/Test).map(res => res.json());
Author: aoakeson, 2016-03-02

3 answers

Supongo que cuando recibes una respuesta vacía (sin carga útil) no necesitas llamar al método json. Bajo el capó, la respuesta XHR es indefinida, se llama JSON.parse(undefined) y se lanza un error.

Puedes saltarte la llamada del operador map:

return this.http.post(API/Controller/Test)/*.map(res => res.json())*/;
 42
Author: Thierry Templier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-01 22:15:08

Otra manera:

Todo mi http.get, post o put call (para uniformidad):

.map(this.extractData)

En extractData (ACTUALIZADO: gracias a raykrow feedback, código corto):

private extractData(res: Response) {        
    return res.text() ? res.json() : {}; ;
}
 46
Author: JeromeXoo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-30 17:43:20

Estrictamente hablando, si su API está devolviendo un código OK sin contenido, debe devolver 204 (sin contenido) - Angular también estaría contento con esto y no trataría de analizar nada. Así que su método controlador se convertiría en:

[HttpPost]
public IHttpActionResult Test()
{
    return NoContent();
}
 7
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-02 10:08:00