Retrieve the object from the data received from the HTTP GET API call

I have a question that has been asked before, but I am unable to achieve the desired result with my current approach.

When my service retrieves data from an API, it returns results in the following format:


{
    "nhits": 581,
    "parameters": {
        "dataset": "communes-belges-2019",
        "rows": 1,
        "start": 0,
        "facet": [
            "niscode",
            "region",
            "nis_code_region"
        ],
        ...

Currently, my service retrieves data like this:


getProvinces(): Observable<any[]>{
    return this._http.get<any>(this.apiProvinces)
      .pipe(
         map((response: any) => response.records as any[]),
         catchError(this.handleError)
         )         
}

It currently returns an Observable<any[]>, but I want to receive an object instead.

To do this, I have defined a class with the following properties:


export class Record{
    region      : string;
    nom_commune : string;
    prov_name_fr: string;
    records?: [];

    constructor(reg: string, commune: string, prov: string) {
        this.region = reg;
        this.nom_commune = commune;
        this.prov_name_fr = prov;
    }
}

I attempted to modify my code by replacing any[] with Record[], but it did not work as expected.


getProvinces(): Observable<Record[]>{
    return this._http.get<Record[]>(this.apiProvinces)
      .pipe(
         map(response => response as Record[]),
         catchError(this.handleError)
         )         
}

In my component, I declared an Observable<Record[]> like this:


public results$!: Observable<Record[]>;

And called the service as follows:


this.results$ = this.apiService.getProvinces();

To display the content in the HTML part, I used:

<div *ngFor="let p of (results$ | async)">
     {{p | json}}
</div>

However, I encountered the error message: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

I'm having difficulty accessing the object. Any guidance would be appreciated as I am new to Angular.

Thank you

Answer №1

When you initialize an observable, it doesn't automatically trigger a request to your api endpoint. To actually send the request and retrieve the data from the observable, you must subscribe to it.

this.apiService.getCountries().subscribe((response) => (this.countryData = response));

This code snippet will send the get request and pass the returned data to the specified callback function. Since get requests are finite observables, there's no need to unsubscribe after receiving the data. However, if you wish to make another request in the future, you'll have to subscribe again.

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

Issue occurred while trying to render a React component with Typescript and WebPack

I am in the process of creating a basic React component that simply displays a page saying Hello. However, I'm encountering an error in my console. My compiler of choice is TypeScript. To set up my project, I am following this guide: https://github.co ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

Angular2 Edit form does not have radio button selected according to the value

When editing a form, the radio button does not appear checked according to the value retrieved. I was able to retrieve the last name from the database, but when trying to bind the gender with the radio button, it does not show as checked. <div clas ...

Is there a way to modify the default lite-server port in the Angular quickstart setup?

I recently obtained the Angular 4 quickstart app and decided to modify the default lite-server port by including "port": 8000 in bs-config.json like this: { "server": { "port": 8000, "baseDir": "src", "routes": { "/node_modules": "node ...

A guide to troubleshooting and resolving the elusive 500 Server Error in Next JS API

Currently, I am in the process of developing a chat bot using the innovative OPEN AI GPT 4 Model within NextJS. However, upon sending a POST request to http://localhost:3001/api/generate, I am faced with a Response displaying a status code of 500 along wit ...

"Troubleshooting: TypeScript is encountering an issue with a generic type that extends from interfaces

I am working with three different interfaces: X.ts export interface X { id: number; name: string;    dateCreated: string; info: string } Y.ts export interface Y { id: number; name: string;    dateCreated: string; category: s ...

Ways to group JSON object in PHP

I have a question regarding JSON object manipulation. Here is an example of the JSON object I am working with: {"ID":"HC","ID_NAME":"Human Capital","TASK_ID":"HC01","TASK_NAME":"Human service 1"} {"ID":"MM","ID_NAME":"Management","TASK_ID":"MM01","TASK_N ...

Error: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

Sending a form using AJAX causes the page to redirect

I have an input type="file" that triggers a form submission upon change. $(document).on("change", "#image-upload", function (e) { $.ajax({ url: '/BlogPost/UploadHomeReport', type: 'POST', data: $('#upload-i ...

Creating Angular components in *ngFor loop

I have set up multiple radio button groups by dynamically populating options using ngFor within a ngFor loop. categories:string[] = [category_1, ..., category_n]; options:string[] = [option_1, ..., option_n]; <fluent-radio-group *ngFor='let ca ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Transform the date format in react.js using information provided by an API endpoint

I'm currently working on a project using React and TypeScript where I need to format the date retrieved from an API. I am able to map over the data and display it, but I'm struggling to convert it into a format like '22 June 2021'. The ...

How can I create a custom validator in Angular 2 that trims the input fields?

As a newcomer to Angular, I am looking to create a custom validator that can trim the input field of a model-driven approach form. However, I have encountered difficulties during implementation. When attempting to set the value using setValue() within th ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

Is it possible to retrieve the original array after removing filters in Angular?

Within my component, I have an array that I am filtering based on a search string. The filtering works as expected when the user inputs characters into the search field. However, I am encountering an issue when attempting to display all records again after ...

Organize the array object by roles using mapping and grouping techniques

Given an object array with roles as keys and values, I want to group them according to the roles assigned. Here is the sample data: { users: [ { firstName: 'Will', lastName: 'Jacob', email: '<a href="/cd ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

Transferring an Image from Angular 7 to Spring-boot

I've been attempting to transfer images from my Angular application to Spring Boot, but I'm encountering issues. When I send a POST request from Angular with the file, Spring Boot doesn't respond as expected. To investigate further, I tested ...

Why is it that my JSON request body is being flagged as invalid now, when a similar request was functioning properly earlier?

I encountered a problem with sending notification data to a discord webhook in the following code snippet, as it kept returning {"code": 50109, "message": "The request body contains invalid JSON."}%. Highlighted below is the ...

Using Enums to resolve fields in a JSONObject

I have multiple JSON responses from the server all containing a specific field called "ac" { "ac": "register" / "upload" / "delete" etc I am looking to create an Enum that can parse this JSON and return the response type enum class ResponseTypes(val json: ...