Tengo un problema cuando intento recuperar el objecto JSON retornado por el script PHP.
Cuando el servidor retorna el objecto JSON y recupero el objecto en Angular obtengo un error.
Si elimino del código la conversión res.json(), el error no aparece y el servidor no retorna nada.
ERROR SyntaxError: Unexpected token in JSON at position 0 at Object.parse (<anonymous>) at Response.webpackJsonp.../../../http/@angular/http.es5.js.Body.json (http.es5.js:797) at SafeSubscriber._next (list-alunos.component.ts:14) at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:238) at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:185) at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:125) at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89) at XMLHttpRequest.onLoad (http.es5.js:1226) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424) at Object.onInvokeTask (core.es5.js:3881)
Tengo un servicio que recuperar la información y un componente que utiliza este servicio:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';
@Injectable()
export class ApiHttpDaoService {
constructor(private http: Http) { }
public getListStudents() {
return this.http.get("http://localhost/obtener_alunos.php");
}
}
Este es el componente:
import { Component, OnInit } from '@angular/core';
import { ApiHttpDaoService } from '../../services/api-http-dao.service';
@Component({
selector: 'app-list-alunos',
templateUrl: './list-alunos.component.html',
styleUrls: ['./list-alunos.component.css']
})
export class ListAlunosComponent implements OnInit {
constructor(private service: ApiHttpDaoService) {
this.service.getListStudents().subscribe(
res => console.log(res.json())
);
}
ngOnInit() { }
}
Y este es el código PHP que retorna el objecto JSON:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
require("conectar_mysql.php");
$vec_res = array();
$result = mysqli_query($conn, "SELECT * FROM alunos");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
array_push($vec_res, array('nome' => $row['nome'], 'idade' =>
$row['idade'], 'morada' => $row['morada']));
}
echo json_encode($vec_res);
}
mysqli_close($conn);
?>
echo json_encode($vec_res); El json_encode($vec_res) no me está devolviendo nada.
Em cambio si construyo el json como un string:
$jsonObj = "{";
while ($row = mysqli_fetch_assoc($result)) {
$jsonObj .= '{' . "nome: " . $row['nome'] . ', ' . "idade: " . $row['idade'] . '}' . ', ';
}
$jsonObj = "}";
Y después hago echo $jsonObj; aparece el string JSON en la network en preview como un string.
Cambie el codigo para esto con el json_enconde no retorna nada: Con el nuevo codigo retorna la string
[{nome: Reynier Lima T�llez, idade: 28}, {nome: Jo�o Matos, idade: 30},
{nome: Joana Bonan�a, idade: 33}]
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
require("conectar_mysql.php");
$vec_res = array();
$jsonObj = "[";
$result = mysqli_query($conn, "SELECT * FROM alunos");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$jsonObj .= '{' . "nome: " . $row['nome'] . ', ' . "idade: " .
$row['idade'] . '}' . ', ';
}
$jsonObj = substr($jsonObj, 0, strlen($jsonObj) - 2);
echo $jsonObj . ']';
}
mysqli_close($conn);
?>
Ahora en la respuesta me llega el objecto pero en el controlador si hago console.log(res._body) me dice que no existe la propriedad "_body".
constructor(private service: ApiHttpDaoService) {
this.service.getListStudents().subscribe(
res => console.log(res._body)
);
}
C:/Users/Reynier/Documents/angular-projects/project/src/pages/list-
alunos/list-alunos.component.ts (14,36): Property '_body' does not exist on
type 'Response'. [1]: https://i.stack.imgur.com/4EtwK.png
Cuando el servidor retorna el objecto JSON y recupero el objecto en Angular Obtengo un error.
= en esta líneaERROR SyntaxError: Unexpected token in JSON at position 0
¿tienes manera de saber qué hay allí?, Si te es posible, intenta devolver el JSON como string a ver que devuelve...