Creating a collection of objects from the specified data type of an HTTP request Promise<Response>

I have a service that makes GET requests to an API server and returns JSON in the form of a Promise. Below is the code for the service:

import { Injectable } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { HttpModule, Http } from "@angular/http";
import { Person } from "./person";
import "rxjs/add/observable/of";
import { Response } from "@angular/http/src/static_response";

@Injectable()
export class PersonService {
  constructor(private http: Http) {}
  public getPeople(): Promise<any> {
    return this.http.get("http://localhost:62066/api/values").toPromise();
  }
}

After importing this service, I attempted to display the data fetched from the Promise as an unordered list:

import { Component, OnInit } from "@angular/core";
import { Person } from "../person";
import { PersonService } from "../person.service";
import "rxjs/add/operator/toPromise";

@Component({
  selector: "app-table-view",
  templateUrl: "./table-view.component.html",
  styleUrls: ["./table-view.component.css"]
})
export class TableViewComponent implements OnInit {
  constructor(private personService: PersonService) {}

  ngOnInit() {
    var people = this.personService.getPeople();
    console.log(people);
  }
}

Below is the log output for 'people':

ZoneAwarePromise {zone_symbol__state: null, __zone_symbol__value: Array(0)} __zone_symbol__state : true __zone_symbol__value : Response {_body: "[{"personID":1,"name":"John","surname":"Doe"},{"personID":2,"name":"Jane","surname":"Smith"}]", status: 200, ok: true, statusText: "OK", headers: Headers, …} __proto : Object

I tried using ngFor directive to loop through the objects but encountered issues with displaying them on the HTML page:

<ul><li *ngFor="let person of people">
{{person.ID}} {{person.name}}
</li>
</ul>

Is there a way to create an array from the Promise or store the Promise data in a list? Apologies for the messy log code formatting.

Answer №1

When working with APIs, it is essential to utilize .json() method:

import "rxjs/add/observable/map"; //<-- include this import


@Injectable()
export class OsobaService {
  constructor(private http: Http) {}
  public getOsobe(): Promise<any> {
    return this.http.get("http://localhost:62066/api/values")
      .map(res => res.json()) //<-- make sure to add this line 
      .toPromise();
  }
}

This function retrieves the body of the response.

Ensure to review your .ts file as well, and correct any local variable declaration that may not be accessible from the html:

export class TableViewComponent implements OnInit {
  osobe: Promise<any> //<-- don't forget to add

  constructor(private osobaService: OsobaService) {}

  ngOnInit() {
    this.osobe = this.osobaService.getOsobe(); //<-- ensure to update
  }
}

Additionally, validate your html code if you are using

var osobe = this.osobaService.getOsobe();

If you assign an observable in your javascript but it's not used as such in your html,

Make use of the async pipe for proper asynchronous handling:

<ul>
   <li *ngFor="let osoba of osobe | async">{{osoba.osobaID}} {{osoba.ime}}</li>
</ul>

Answer №2

Give this a shot:

Fetch data from "http://localhost:62066/api/values" using the HTTP GET method and then parse the response to JSON format.

Answer №3

Ensure to include both the 'then' and 'catch' functions in your service function call:

this.userService.getUsers().then((data) => {console.log(data);}).catch((err) => {console.log(err);});

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

Error: Can't find module ng-uikit-pro-standard

I am currently working on implementing datatables in Angular with material design. To achieve this, I am referencing a tutorial from this source. The tutorial instructs to import the MdbTableDirective, MdbTablePaginationComponent, and MdbTableService from ...

Creating a generic class for third-party API requests in NestJS

I'm working on a NestJS application that involves making third-party API requests. Every function requires the same code to retrieve data, causing repetition. How can I streamline this process by creating a common class for handling GET or POST reque ...

Creating dynamic HTML in Angular 2 can be achieved by utilizing directives, data

I am interested in building an accordion feature in angular2 without needing to duplicate the structure each time it is used. Similar to how we can create plugins in jQuery and include HTML code, I would like to find a way to achieve this in Angular2. Ca ...

Implicated Generic in TypeScript

Is there a way to simplify my class A implementation? export class A<TB extends B<TC>, TC> implements TD<TB, TC> { make(): TC {} } Currently, I have to specify the TC type every time I create an instance of A: class CTest {} class BTes ...

Custom TailwindCSS Theme Builder

My goal is to implement a variation of themes and be able to switch between them using tailwind CSS. I came across a tutorial on YouTube regarding this topic in JavaScript youtube video, but I am working with TypeScript and encountering issues with a cus ...

Angular version 16+ is incompatible with Three.js and does not function properly together

I am attempting to integrate three.js into my Angular 16 project and encountering the following error message: npm i @angular-three/core npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email&# ...

Opening an HDF5 file and converting it to a numpy array in Python

Is there a way to import a .hws file as a numpy array? After reading about the HDF5 based format in this source, I found some potential solutions in this documentation. However, when following the instructions provided: hdf5_file_name = '/reg/d/psd ...

Leveraging Observables for Angular Drag and Drop Functionality

Struggling to use an Observable as the data source for a material drag and drop feature. Working on a kanban board with swimlanes containing movable items that need backend updates. Planning to implement socket.io for real-time item movement in the shared ...

The absence of certain attributes in TypeScript

class DeploymentManager { import { observable, action, makeAutoObservable } from "mobx" public deploymentQueue = observable<IDeploymentProject>([]); public inProgressProjects = observable<IDeploymentProject>[]; public s ...

I'd like to know the location of the SelectorEvent definition and the proper way to import it for type-checking

In my current project, I have implemented the following code snippet to create a select interaction, integrate it into a map, and execute certain actions when a feature is selected or deselected: const select: Select = new Select({ hitTolerance: 5, mul ...

Is it possible to expand a div container dynamically when a button is pressed?

Currently, I am honing my skills in front-end web development by working with Angular 6 and the Materialize Framework. Although I am a beginner in this field, I find the use of cards in Materialize quite intriguing. One specific feature I'd like to im ...

What is the significance of `(<typeof className>this.constructor)` in TypeScript?

After inspecting the source code of jQTree, written in Typescript, available at https://github.com/mbraak/jqTree, I came across the following snippet: export default class SimpleWidget{ protected static defaults = {}; ...

Experiencing a problem with C code

Could someone please assist me in identifying the issue with this code? The code compiles without any errors, however, when I try to input data into an Array of Objects of a structure, the data does not get entered after one loop. #include<stdio.h> ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

What impact does control flow have on narrowing variable types?

Having reviewed this particular question, my current focus is on understanding how variables can be narrowed down using control flow. An example: type T1 = { a?: { b: string } } const t1: T1 = {} t1.a.b // displays error, possibly undefined t1.a ...

Unable to showcase Google Maps in VS 2015 with Angular 2 integration

Here is a snippet of code for a component I created: import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles: [`.sebm-google-map-container { height: 300px;}`], template: `<sebm-google-map [latitude]="la ...

How do I go about implementing date filtering in Matlab for a table?

I am facing an issue with Matlab. I have a table containing dates in one column and hundreds of rows, and I need to filter out only the dates that are after a specified date. Below are the first ten rows of the table: a = 17×1 table nav_date ___ ...

Can you explain the meaning of the TypeScript code snippet below?

Recently, while going through the declaration file of reflect-metadata library, I came across the following code snippet. It appears that the function metadata is expected to return an object with 2 functions. Could someone kindly explain the purpose of ...

What is the best way to select multiple items in an array?

This is my code. How can I pass multi-select values with an array to a PHP file called modelsearch.php <p> <label>Country:</label> <select multiple="multiple" name="country[]" class="qs_carlocation1 carlocations" onChange ...

How to disable the action button in a Kendo dialog in Angular 4

I need to implement a feature where the 'Save' button is disabled if the value of 'TotalUnits' is less than 0. How can I achieve this functionality for the 'Save' button? Main Component: OpenAllocationDialog(data: any) { ...