Search code examples
phpangularlumenangular-httpclient

How to get an array of data from a php API ( laravel lumen) in Angular


I'm stuck as it is my first time using Angular and I might have not understood some basics.

I've made a PHP API that returns data from a MySQL database, and I get them in angular using HttpClient.

The call to the database is:

public function showOneCoursBy($id){
    $results = DB::select("select * from cours where id_cours = ".$id);
    return $results;
}

Accessing the API page I get:

[{"id_cours":1,"id_exercice":1,"titre":"XXX","description":"XXX","contenu":"XXX","mediaPath":"XXX","dateDebut":"0000-00-00","dateFin":"0000-00-00"}]

So it seems right.

In Angular, I get the data with

  constructor(
    private firestore: AngularFirestore,
    private http: HttpClient,
    public db: AngularFirestore
  ) {
    this.http.get('http://localhost:3000/cours/').
    toPromise().then(data => {
      console.log(Object.keys(data).map(key => ({type: key, value: data[key]})));
      }
    );
  }

In a service, the console.log do return

(2) […]​
0: {…}​​
type: "0"​​
value: Object { id_cours: 1, id_exercice: 1, titre: "Premier Cours", … }
<prototype>: Object { … }
1: {…}​
type: "1"​
value: Object { id_cours: 2, id_exercice: 2, titre: "Cours n°2", … }
<prototype>: Object { … }
length: 2​
<prototype>: [

But how can I get only one of those element as an array? Or access only one property?


Solution

  • You can simply declare an interface for the Object

    export interface Exercice { 
      id_cours: number;
      id_exercice: number;
      titre: string;
      description: string;
      contenu: string;
      mediaPath: string;
      dateDebut: string;
      dateFin: string
    }
    

    You access the data by typing your response as Exercice

     this.http.get('http://localhost:3000/cours/')
       .pipe(take(1))
       .subscrible((response: Exercice[]) => {
         response.forEach(exercice => console.log(exercice.titre));
       });