Need help assigning returned PHP data to Angular 2 object array

  angular, php

I’m not sure how to use the data returned from my PHP code inside my angular class. I would like to be able to use my shelf component to take the data returned from the backend and create an array of Book. I’m receiving the data from PHP fine, I can see it returned when i check the headers. I’m just not familiar with Angular enough to know how to assign the returned data to the array of type Book.

Book interface

export interface Book {
    id: number;
    title: string;
    rating: number;
}

Shelf component (where I want to parse the data and use each as a Book)

import { Component, OnInit } from '@angular/core';
import { Book } from '../book';
import { BooksService } from '../books.service';

@Component({
  selector: 'app-shelf',
  templateUrl: './shelf.component.html',
  styleUrls: ['./shelf.component.sass']
})
export class ShelfComponent implements OnInit {

  books: Book[] = [];

  constructor(private booksService: BooksService) {
    
  }

  ngOnInit() {
    this.getBooks();
  }

  getBooks(): void {
    this.booksService.getBooks().subscribe( response => {
      console.log("success: " + response);
    }, 
    err => {
      console.log("error: " + err);
    });
  }
}

Books service (where i’m sending the request for the data to be used as Book(s) )

import { Injectable } from '@angular/core';
import { Book } from './book';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

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

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' })
  };

  constructor(private http: HttpClient) { }

  getBooks(): Observable<Book[]> {
      return this.http.post<Book[]>("http://localhost/Projects/index.php", this.httpOptions )
      .pipe(map(response => response ));
  }
}

PHP code

$books[] = [ 'id' => '1', 'title' => 'test', 'rating' => '5'];
$books[] = [ 'id' => '2', 'title' => 'test2', 'rating' => '6'];

echo json_encode($books);

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.