How to get a response from a php to angular

1

I have a problem that when I run my php file, a json returns to me and I want this answer to be angular. But he does not read it to me. This would be the php file:

<?php
try{
 $conexion = new PDO('mysql:host=localhost;dbname=prueba','root','');       
} catch (PDOException $e){
    echo "Error" . $e->getMessage();
    die();
}
$productos =  $conexion->prepare("SELECT * FROM productos");
$productos->execute();
$productos = $productos->fetchAll();

$userData = array();
foreach ($productos as $producto) {
    $userData['AllUsers'][] = $producto;
}
echo json_encode($userData);
?>

And this would be the service that would use it:

constructor( public http: HttpClient ) { 
    console.log('listo');
    this.listar();
}
private listar(){
  this.http.get('assets/api/productos.php') //info.json funciona y tiene el mismo contenido 
     .subscribe((data) => {
      console.log(data);
    });
}

The problem was solved by enabling a second server '

I would like to know how I would upload it to a hosting, should I just do a "ng build --prod"? because as I put a "localhost: 1234" to listen to the php files.

    
asked by Anthony DC 31.08.2018 в 21:17
source

1 answer

0

Look, what I try to do in my projects with Angular is the following to obtain data from a Database:

PHP example

<?php

  //Declaracion de cabeceras del sistema
  header("Context-type: application/json;");
  //Inclusion del archivo respectivo para la conexion con la BD
  require '../conexion.php';
  //Declaracion del array para codificar en formato JSON la variable mensaje
  $resultado = array();
  //Evaluamos si la conexion a la BD se realiza correctamente
  if ($mysqli)
  {
    $mysqli->set_charset('utf8');
    $resultadoConsulta = $mysqli->query("SELECT * FROM productos");

    $data = array();

    while ($row = $resultadoConsulta->fetch_assoc())
    {
      $data[] = $row;
    }

    echo json_encode($data);
  }
  else
  {
    //Para obtener el resultado de la variable $resultado tienes que hacer algo mas en Angular.
    $resultado['mensaje'] = "Problema de conexión";

    echo json_encode($resultado);
  }

 ?>

Once the data has been verified by the server, we can proceed with making the respective requests to the server to obtain and process said data:

  

Note: It is advisable to use services to obtain a greater structure of the functions and methods. This as a recommendation for the people who come here.

We use the command: ng generate service services/nombrearchivo , when I refer to services is the name of the folder, it can be cualquiercosa , this for a greater facility to structure your files.

Angular - Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ConsultaComunService {

  constructor(private http: HttpClient) { }

  //Declaramos la funcion para recuperar los datos procesados por el constructor de la clase
  public obtenerProductos()
  {
    return new Promise(
      resolve=>{
        this.http.get('url.php')
        .subscribe(
        data => resolve(data)
        )
      }
    )
  };
}

Angular - Component

import { Component, OnInit, ChangeDetectionStrategy, Input  } from '@angular/core';
//Importacion de servicios
import { InventarioService } from './../services/nombrearchivo.service';

@Component({
  selector: 'app-producto',
  templateUrl: './producto.component.html',
  styleUrls: ['./producto.component.css']
})

export class ProductoComponent implements OnInit {
  //Variables donde se almacenan los datos obtenidos por el servicio
  listadoProducto:any;
  productos:any;
constructor(private _serviceProducto:ConsultaProductoService)
  {

    //Recuperar los datos del servicio para obtener los productos.
    _serviceComun.obtenerImpuesto()
    .then(data=>{
      this.listadoProducto = data;
      this.cargarProductos();
    })
    .catch(err=>{
      console.log(err);
    });


  };

//Preparamos la funcion para obtener el listado de los productos
  cargarProductos()
  {
    this.productos = this.listadoProductos;
    //Evaluamos si el listado obtenido cuenta con registros, con la finalidad de hacerle saber al usuario que no cuenta con registros.
    if (this.categorias.length > 0)
    {
      this.mensajeSinProductos = false;
    }
    else
    {
      this.mensajeSinProductos = true;
    }
  };
}

Vista

Already in this part you just have to go through the data with the angle directive *ngFor :

*ngFor="let producto of productos" .

  

To consider:

  • I recommend you to enable a second server (that keeps listening all the time) to be able to execute the PHP files, what I try to do is use the command php -S 0.0.0.0:1234 , obviously, you have to go to the path where you have your files PHP that I think is in the assets/api folder.
  • You can use xampp to enable your Databases and to which you can make the respective CRUD.
  • Declares very well all your models, both in the view and in your component of typescript, because when sending it to production you will have certain problems if you do not do it.
  • And finally, you should create a file called: proxyconfig.json in the same division of package.json
  • The content should be as follows:

    {      "/ authentication": {           "target": " link ",           "secure": false,           "changeOrigin": true        }   }

  • We modified the package.json file on line 6 by the following instruction: "start": "ng serve --proxy-config proxyconfig.json", later you use the ng serve --proxy-config proxyconfig.json command to start the angular services.

  • I hope it serves you!

        
    answered by 31.08.2018 в 23:30