Andrey castillo
Andrey castillo

Reputation: 1

Angular http client

I have a problem with angular, the problem is the following, the method to obtain an http client, does not get any value from an api in php that is listening on the localhost port: 123. The php code would be the follow

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

//Get todos los usuarios
$app=new \Slim\App;

//Get todos los usuarios
$app->get('/api/clientes', function(Request $request,Response $response){
    include "../src/db.php";
    $query="select * from users";

    $result = mysqli_query($con,$query);    
    if (!$result) {  
        die("Query fail");
    }else {
        $row_cate = mysqli_num_rows($result); 

        if($row_cate == null){
            echo "no existen datos en la dbo";
        }
        else{
            $users=array();
            $cont=0;
            while ($row = mysqli_fetch_array($result)){
                $producto[$cont]=array(
                    "id" => $row['id'],
                    "name" => $row['name'],
                    "email" => $row['email']
                );
                $cont++;
            }
            echo json_encode($producto);
        }
    }
});

and the angular client method is as follows.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from './user.model';
import { Observable } from 'rxjs';

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


  constructor(private http:HttpClient) { }

  get(){
    const url="http://localhost:1234/public/api/clientes";
    return new Promise(
      resolve=>{
        this.http.get(url)
        .subscribe(
          data=>resolve(data)
        )
      }
    );
  }

}

I would appreciate your help.

Upvotes: 0

Views: 72

Answers (2)

Andrey castillo
Andrey castillo

Reputation: 1

I already managed to solve the error, the truth was a beginner error, the problem was in the api, I had not put the headers that allowed to perform the procedures "get", "post", etc in php

Upvotes: 0

Vladimir Prudnikov
Vladimir Prudnikov

Reputation: 7242

Your code in get() method is invalid. Here is a better code if you want it to return Promise.

get(): Promise<any> {
  const url="http://localhost:1234/public/api/clientes";
  return this.http.get(url).toPromise();
}

Also, make sure your server responds with the data you expect

If you are just getting started with Angular, then my advice to you is to learn RxJS and use Observables instead of Promises with Angular.

Upvotes: 1

Related Questions