Angular 11 component encountering issues with accessing server-side data

Recently, I encountered an issue when trying to connect the PHP API with the Angular service to retrieve data from the database. I am uncertain whether the problem lies within the service, the component.ts file, or the HTML section. Therefore, I have shared my code here in hopes that you can assist me in resolving it.

The specific error I am facing is:

ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Interestingly, I am able to see the data from the server when using a console.log() statement, but the data does not populate in the list.

carservice.ts

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

import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

import { Car } from './car';

@Injectable({
  providedIn: 'root'
})
export class CarService {
  baseUrl = 'http://localhost/api/car';
  
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }
  
  
  
  constructor(private http: HttpClient) { }

  getAll(): Observable<Car[]> {
    return this.http.get<Car[]>(this.baseUrl+'/read.php/')
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }   
}

voiturecomponent.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Car } from 'app/car';
import { CarService } from 'app/car.service';

@Component({
  selector: 'app-voiture',
  templateUrl: './voiture.component.html',
  styleUrls: ['./voiture.component.css']
})
export class VoitureComponent implements OnInit {
  cars : Car[] = [] ;


  constructor(private carService: CarService, private router:Router) { }

  onBackButtonClick() :  void {
    this.router.navigate(['/ajout-car']) ;  
  }

  
    ngOnInit(): void {
      this.carService.getAll().subscribe((data: Car[])=>{
        console.log(data);
        
        this.cars = data ;
       
      })  
    }
}

voiturecomponent.html

<div class="main-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                 

                  
                  <div class="col-md-12">
                  <div class="card-header">
                  <h4 class="title" ><strong> Liste Voiture </strong></h4>
                </div></div>
              
                <div class="card-body">
                  <span type="button" 
                        class="btn btn-fill tn-secondary pull-right"
                        (click)=onBackButtonClick() >
                        <i class="fa fa-plus-square" aria-hidden="true"></i>
                        Ajouter Voiture 
                  </span>
                  <div class="clearfix"></div>
                  </div>

                <br>
      
 <div id="theList"> 

                    
  
  <div class="container">
    <div class="col-md-12">
  <table class="table table-bordered " >
    <thead>
    <tr>
      <th>Id</th>
      <th>Série</th>
      <th>Model</th>
      <th>Action</th>
    </tr>
    </thead>
    
   <tbody>
      <tr *ngFor="let car of cars ">
      <td>{{car.id}}</td>
      <td>{{car.model}}</td>
      <td>{{car.serie}}</td>
      <td>

   
        <button type="button" class="btn btn-info btn-fill btn-warning btn-sm btn-space">
          <i class="fa fa-pencil" aria-hidden="true"></i>
        </button>
        <button type="button"  class="btn btn-info btn-fill btn-danger btn-sm btn-space" >
          <i class="fa fa-trash-o" aria-hidden="true"></i>
          </button>
    

      </td>
     </tr> 
    </tbody>
  </table>

</div>
</div>
 </div>
</div>
</div> 
</div>
</div>
</div>

Your assistance in resolving this issue is greatly appreciated.

Answer №1

Here is the API code snippet for accessing car data:

<?php
// Setting up required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// Establishing database connection and including necessary files
include_once '../connect.php';
include_once '../objects/car.php';

// Creating instance of the Database and Car objects
$database = new Database();
$db = $database->getConnection();
$car = new Car ($db);

// Fetching and displaying car data
$stmt = $car->read();
$num = $stmt->rowCount();

if($num>0){
    $car_arr=array();
    $car_arr["records"]=array();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);

        $car_item=array(
            "id" => $id,
            "model" => $model,
            "serie" => $serie,
        );

        array_push($car_arr["records"], $car_item);
    }

    http_response_code(200);

    echo json_encode($car_arr);
}
else{
    http_response_code(404);

    echo json_encode(
        array("message" => "No cars found.")
    );
}
?>
<?php
class Car {
    private $conn;
    private $table_name = "cars";

    public $id;
    public $model;
    public $serie;

    public function __construct($db){
        $this->conn = $db;
    }

    function read() {
        $query = "SELECT p.id, p.model, p.serie FROM " . $this->table_name . " p; ORDER BY p.id DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When it comes to the CSS `:visited` pseudo-class, I have

I'm having trouble changing the color of the anchor tag and blurring the image after visiting the link. Despite my CSS code, only the color is changing and the image remains unchanged. Here's my CSS code: <style> .image123{ paddin ...

Changing color of Font Awesome Icons upon hover, without any animation

I need assistance with changing the color of font awesome icons on hover without any animation. Specifically, I want the icon colors to transition from indigo to blue and finally red when a user hovers over them, without the colored icon appearing abruptly ...

HTML Input Hidden : Completely Concealed

I have been working on creating a 'captcha' for my website, and this is the code I am using: <form class="captcha" method="post"> <label><?php echo $captchas ?></label><br> <input name="captcha" /> <input t ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

Creating an event listener to conceal a popup with a click

One of the key elements in my project is a popup with the unique identifier of myPopup. The class show is responsible for toggling the display property from none to block, allowing the popup to appear on the screen. As a beginner in using event handlers, ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

Using Vuejs to dynamically render raw HTML links as <router-link> elements

Hey there, I'm just getting started with VueJS and I've been doing some interesting experiments. I created a backend service using Python/Flask that provides me with a string of HTML code containing many tags. My goal is to render this HTML insid ...

What is the best way to utilize JavaScript in order to eliminate a tag when an option is chosen within an HTML form?

I'm in the process of designing a website for an artist. The website includes a contact form, and I'm currently working on a JavaScript script to remove the hidden class that I applied to the commission rules section. The goal is to make this sec ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

Learn how to upload files from Angular 2 and send them to a server URL using ng2-fileupload

I am currently utilizing ng2-file-upload for file uploads on the front end. Within my HTML, I have the following code: <input type="file" ng2FileSelect [uploader]="uploader" /> In my TypeScript file, I receive the uploaded file in a change event ...

The trouble with React Navigation encountered with TypeScript: This Entity Cannot Be Invoked

Currently, I'm facing a typescript issue after upgrading to React Navigation 5. The specific error message reads: There is an issue with calling this expression. The union type '{ <RouteName extends "Stack1Screen1" | "Home&quo ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

Place an element in the middle of the svg

I have a D3.js svg element measuring (1000,1000) with a circle positioned randomly, such as (100,200). My goal is to adjust the svg so that the circle is centered at (500,500). I want to create a function that can do this for any randomly positioned circl ...

Issue with horizontal scrolling functionality in DataTables

I have a table with over 10 columns, and I am using datatables to display the data. I have enabled horizontal scrolling due to the large number of columns, but the scroll is not appearing. Can someone please assist me with this issue? Here is a screenshot ...

Is it ideal for ad-hoc values to reside within the component as class properties, or is there a better approach

Imagine a scenario where a recipe website features a recipe-list component that displays cards of individual recipes: <ul class="recipe-list"> <li *ngFor="let recipe of recipes" (click)="displayRecipe(recipe)"> ...

Oops! You can't switch to `multiple` mode on a select dropdown once it has already

Here's where the issue lies: This is the code I am referring to: <div fxFlex.gt-lg="100" fxFlex="100" *ngIf="requestAction == 'add'"> <div class="pb-1"> <md2-select plac ...

What could be causing the embedded dropdown to automatically select the initial option every time?

I am encountering an issue with a page that includes an html table rendered using node with express and ejs. The table contains a select dropdown in one of the cells, and it populates correctly with the right values. However, regardless of which option I ...

Is it possible to utilize TypeScript version 2.0.6 in conjunction with Visual Studio 2017?

Is it possible to utilize TypeScript 2.0.6 with Visual Studio 2017, or do I need to use a version greater than 2.1? Also, can you explain the difference between Microsoft.TypeScript.Compiler and Microsoft.TypeScript.MSBuild? If I don't have Microsof ...