Encountering an error while performing a GET request in Angular: Issue arises from inability to locate a differ that supports the object '[object Object]'

The tab1.page.ts is responsible for fetching a list of places through a GET request. Laravel returns the data in JSON format.

tab1.page.ts

export class Tab1Page implements OnInit {

  places$: Place[];

  constructor(
    private placesService: PlacesService
  ) {}

  ngOnInit() {
    return this.placesService.getPlaces()
    .subscribe(data => this.places$ = data);
  }

}

This is the service I am using to retrieve the list of places. places.service.ts

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Router } from '@angular/router';
import { Place } from '../models/place.model';

@Injectable({
  providedIn: 'root'
})
export class PlacesService {
constructor(private http: HttpClient, private router: Router) { 
   }
getPlaces () {
    return this.http.get<Place[]>(environment.getBaseAddress() + 'places/get');
  }
}

An error occurs in the console: "cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

I have provided the structure of the JSON as requested.

{
    "places": [
        {
            "id": 1,
            "place_id": "coktail",
            "approved": "Review",
            "requested_by_staff": "yes",
            "activities_associated": "get work done",
            "address": null,
            "photo_places": null,
            "id_owner_user": null,
            "created_at": "2021-01-02T14:39:09.000000Z",
            "updated_at": "2021-01-02T14:39:09.000000Z"
        },
        {
            "id": 2,
            "place_id": "librino",
            "approved": "Review",
            "requested_by_staff": "yes",
            "activities_associated": "get work done",
            "address": null,
            "photo_places": null,
            "id_owner_user": null,
            "created_at": "2021-01-02T14:45:35.000000Z",
            "updated_at": "2021-01-02T14:45:35.000000Z"
        },
        {
            "id": 3,
            "place_id": "librino2",
            "approved": "Review",
            "requested_by_staff": "yes",
            "activities_associated": "get work done",
            "address": null,
            "photo_places": null,
            "id_owner_user": null,
            "created_at": "2021-01-02T14:46:19.000000Z",
            "updated_at": "2021-01-02T14:46:19.000000Z"
        }
]
}

Usercontroller.php

public function getPlaces(){
        $places =  Place::all();
        if ($places)
            return response()->json(['places'=>$places], 200);      
        else
            return response()->json("places not found", 500);
    }

tab1.page.html

<div *ngFor='let place of places$'>
    <ion-grid>
      <ion-row>
          <ion-col>
            <ion-card routerLink="/place-details" routerDirection="forward" style="background-image: url('https://oecdenvironmentfocusblog.files.wordpress.com/2020/06/wed-blog-shutterstock_1703194387_low_nwm.jpg?w=640');height: 150px;">
              <ion-grid>
                <ion-row>
                  <ion-col>
                    <ion-badge item-start>Type of activity {{ place.place_id }} </ion-badge>
                  </ion-col>
                </ion-row>
              </ion-grid>
              <ion-grid style="padding-bottom:0px;">
                <ion-row>
                  <ion-col>
                      <ion-card-title>Location {{ place.activities_associated }}</ion-card-title>
                  </ion-col>
                </ion-row>
              </ion-grid>
            </ion-card>
          </ion-col>
      </ion-row>
    </ion-grid>
  </div>

What could be causing this issue?

Answer №1

The error message indicates that you are attempting to iterate over an object using ngFor, which requires an array for iteration. To resolve this, make the following adjustment as the array information is contained within the object places$:

<div *ngFor='let place of places$?.places'>
   <!-- remaining code here -->
</div>

Moreover, it is advisable to reserve the use of $ solely for observables. In this scenario, since it's an array, it would be best practice to rename places$ to just places.

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

Retrieve the state using a custom hook in a different location

My custom hook is designed to retrieve and parse a JSON object from the DOM like this: export const useConfig = () => { const [config, setConfig] = useState<Config>(); useEffect(() => { if (document) { const config ...

Encountering a TypeError with Angular 5 Interceptor: The do function is not recognized when using next.handle(...)

While developing an angular interceptor to verify the validity of my auth tokens, I encountered an issue where the do method is not recognized by angular. The alternative solution involving subscribe was effective, but it led to duplicate requests being se ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Ways to transfer information from the parent component while the component is repeatedly utilized on the page

Consider the following situation within Angular 6: There is one upload component that is being utilized twice on the same page. By clicking the add button on any upload component using a behavior subject, data specific to that upload component can be obt ...

Issue with Docker Compose: Containers cannot communicate with each other through the browser

Three services have been configured in Docker Compose: a frontend (Angular 11), a backend, and a dataservice (both built with Typescript/Express). The frontend sends requests to the backend, which then calls the data service to respond to the request. This ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

What is the best way to implement a dynamic back button in Next.js?

Being familiar with creating a standard back button, I am now eager to craft one that directs the user back by one step in the URL rather than returning to the previous page. This way, I can utilize the button in various locations without needing to alter ...

Does Angular 6/7 typically employ Eager or Lazy loading by default?

Is it necessary to manually implement Lazy Loading for the modules, or does Angular 6/7 handle this automatically? ...

Exploring the elements in a JavaScript array

Currently, I am working on a project that involves a website where users can upload .csv files for processing. The main goal is to extract the data from the uploaded file and compare it with the existing file on the website using JavaScript. My challenge l ...

Display a two-dimensional array within a textarea alongside four radio buttons for user interaction

I'm facing an issue where I have an array that needs to be displayed in a textarea as the question and on four radio buttons as the answers. The questions and answers are combined in one array with the first element being the question and the rest bei ...

Split the concatenated string into separate lines according to a specified criterion, then insert line breaks

I am receiving a dynamic text from the database via an API call in this format: Test 1<br>Test 2<br>Test 3 How do I split this string at each 'br' tag and insert line breaks? I want to display the string as follows: Test 1 Test 2 Tes ...

Mistakingly passing an array in C++ functions

I have a project for my class where I need to create a binary search tree of criminal names with up to 8 attributes per criminal. To accomplish this, I have set up a string array called `att[]` that reads in the attributes for each criminal. However, when ...

The Angular2 promise resolves before the web service call has finished executing

I have a service in Angular 2 that contains a function responsible for providing data for a dropdown list. This particular function returns a promise. Below is the code snippet from the service: getStuff(): Promise<Stuff> { return t ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Populate an array with the contents of a different array

I am currently facing an issue with a function that checks for errors in an XML file. When the function identifies errors, I store them in an array to display after the successful results. However, when iterating through the errors to print them, each erro ...

Error: JSON parsing error due to mixed data types in the syntax

Here is an example of JSON data: {"tasks" : [ { "id" : "27604_11", "quality" : "A4", "position" : "183567", "profile" : "https:\/\/example.com\/gallery\/profiles\/8764_2. ...

Incorporate Material Design Icons into your NPM Electron React application for sleek visuals

I am currently exploring how to incorporate Material Design Icons into an NPM Electron project with Webpack 4. The Google Github page suggests that the icons can be easily installed using npm install material-design-icons. However, based on this discussion ...

What is the proper way to assign a negative value to every element in an array?

In my program, I prompt the user to input a specific number of elements in an array. After initializing all elements to zero, I attempted to set them to -1, but encountered a segmentation fault issue. What would be an alternative approach to setting all ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Injecting Parameters into Angular Component Providers

One of my components inherits from another component - @Component({ template: '', providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TComp), multi: true, }, ] }) export abst ...