Angular, PHP with MYSQL error

0

I have a problem when I try to recover the JSON object returned by the PHP script.

When the server returns the JSON object and retrieves the object in Angular I get an error.

If I delete the res.json () conversion from the code, the error does not appear and the server does not return anything.

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)

I have a service that retrieves the information and a component that uses this service:

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

This is the component:

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() { }
}

And this is the PHP code that returns the JSON object:

<?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); The json_encode ($ vec_res) is not returning anything.

Instead, if I build the json as a string:

$jsonObj = "{";
while ($row = mysqli_fetch_assoc($result)) {
        $jsonObj .= '{' . "nome: " . $row['nome'] . ', ' . "idade: " . $row['idade'] . '}' . ', ';
    }
$jsonObj = "}";

And then I echo $ jsonObj; the JSON string appears in the network in preview as a string.

Change the code for this with the json_enconde does not return anything: With the new code returns the 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);
?>

Now in the answer the object arrives but in the controller if I do console.log (res._body) it tells me that the property "_body" does not exist.

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
    
asked by Reynier Téllez 21.07.2017 в 14:10
source

0 answers