Converting JSON to objects in Angular 2 using Typescript

Being new to Angular2 and Typescript, I am currently in the learning phase. I am trying to retrieve data from a REST service and then populate a list with this data obtained from the service. The API link I am using is http://jsonplaceholder.typicode.com/users/1

This is my HttpTestService.ts code;

import {Component} from '@angular/core';
import {Http} from '@angular/http';
import {Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import 'rxjs/add/operator/map';

@Injectable()
export class HTTPTestService{
  constructor(private _http:Http){}
    getUser(){
      return this._http.get("http://jsonplaceholder.typicode.com/users/1")
      .map(res=>res.json());
    };
}}

Below is my HttpTestComponent.ts;

import { Component } from '@angular/core';
import {HTTPTestService} from './http-test.service';
import { User } from './user';

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Post Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Get Data(w Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>
  `,
  providers:[HTTPTestService]
})

export class HTTPTestComponent{
  getData:string;
  getPromiseData:string;
  postData:string;


  constructor(private _httpService:HTTPTestService){}

  onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(        
      data =>this.getData = JSON.stringify(data),
      error=>alert(error),
      ()=>console.log('Finished Get')      
    );         
  }}

Also, take a look at my User.ts file below

 export class User{
  constructor(public id: number,public name:string) { }
 }

I am looking for guidance on how to initialize and add items to my User class in order to create a generic list.

Sincere regards

Answer №1

It appears that you are asking how to create a new instance of the User object and pass specific data, such as the id and name.

private userList: Array<User> = new Array<User>();

onGet(){
    console.log('Fetching user information.');
    this._httpService.getUser().subscribe(        
      data => this.parseUser(data),
      error=>alert(error),
      ()=>console.log('Finished Fetch')      
    );         
  }

parseUser(data) {
   let user = new User(data.id, data.name);
   this.userList.push(user);
}

To create a list of users, simply create an array of User objects like this:

private Users: Array<User> = new Array<User>();
don't forget to import the User object.

UPDATE. For testing purposes, modify this section

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Fetch Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Send Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Fetch Data(with Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>

    <div *ngFor="let user of userList">
       <p>Id: {{user.id}}</p>
       <p>Name: {{user.name}}>/p>
       <br />
    </div>
  `,
  providers:[HTTPTestService]
})

Once the response is received, angular will display the data :)

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

How can you effectively blend Vue/Angular with other JavaScript resources to enhance your development process?

My curiosity lies in understanding how front-end javascript libraries such as Vue and Angular can seamlessly integrate with other libraries and assets. For instance, if I were to procure a website template already equipped with additional javascript, is it ...

Guide on importing a markdown file (.md) into a TypeScript project

I've been attempting to import readme files in TypeScript, but I keep encountering the error message "module not found." Here is my TypeScript code: import * as readme from "./README.md"; // I'm receiving an error saying module not found I als ...

Angular2 Window Opener

Trying to establish communication between a child window and parent window in Angular 2, but I'm stuck on how to utilize window.opener for passing a parameter to Angular 2. In my previous experience with Angular 1.5, I referenced something similar he ...

The search for the "index" view in the views directory failed - Angular Universal SSR encounters errors with Firebase Cloud Functions

Currently, I am working through a tutorial on Server Side Rendering with Angular, Angular Universal, & Firebase 2021. The goal is to deploy my Angular universal project to Firebase hosting using Firebase functions. I managed to set up the emulator suc ...

Error encountered while attempting to import a virtual module, import resolution unsuccessful

I've been working on creating type declarations for a Javascript module in Typescript. My goal is to define interfaces using what I believe is a virtual module. Initially, I had no trouble defining the base module types. However, when attempting to im ...

Setting up validators for an entire FormGroup in Angular ReactiveForms can be achieved by iterating through the

In my current project, I am dealing with a complex form that includes multiple fields. For each field, I have implemented various validators to ensure data integrity. For example, for the 'surname' field, I have the following validators: this.s ...

CRUD operation: The DELETE method is invoked prior to the user's request

Upon opening the localhost:4200 app, I noticed an old delete request already present. Even when I try to use the new delete request by clicking the button, it gives me a 404 (Not Found) error. However, manually entering the URL into the search bar does del ...

Issue with package.json not recognizing the 'exports' property for both ESM and CommonJS npm packages

I am facing challenges in configuring my npm library to support subpath imports/requires using the "exports" field in the package.json. To provide some context, the package.json file allows you to selectively expose files based on the runtime (commonjs OR ...

Converting an array into an array of objects using Node.js

I currently have a Node.js REST API that generates an array structured like this: [["Benni", 24, "Whatever"], ["Paul", 23, "Whatever"]] In order to integrate this array into an Angular Material table, I need to transform it into the following format: [{ ...

Tips for displaying items only if enough space is allocated for them using ngFor in Angular2

Is there a way I can use a custom pipe (with ngFor) to do this? At the moment I am rendering all the tags using ngFor and positioned them in a row using css flex. <div *ngFor="let tag of tags" class="tag" [ngClass]="&apo ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Angular 14 struggles with Bootstrap installation

I encountered an issue while trying to install Bootstrap in Angular 14 using "ng add @ng-bootstrap/ng-bootstrap" in PhpStorm IDEA. How can I resolve this error situation? Error Error ...

Combining Layouts and Providers: A Guide to Using Both on a Single Page

I am facing an issue with my provider that is responsible for refreshing a token by making a request to the server. Additionally, I have a basic layout featuring a sidebar that I want to use only on a specific route. However, I am unsure about where to add ...

Incorrect positioning of AnyChart within a reusable component (Angular version 9.1.3, Bootstrap 4.4.1, Anychart version 8.7.1) causing display issues on the DOM

I have created a test dashboard featuring two Bootstrap cards, each containing an Anychart column chart. The primary objective is to experiment with reusable components. For those interested, here is the code link on Stackblitz Upon running the code, my ...

`I am encountering an "Invalid" error when checking @angular/[email protected] with the command "npm ls rxjs". What steps should I take to resolve this issue?`

Upon running "npm ls rxjs," the following output is displayed: +-- @angular-devkit/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e6eaf7e0c5bcabb4abb5a8ebe0fdf1abb6">[email protected]</a> | `-- <a href="/cdn- ...

The JSX Configuration in TypeScript: Comparing ReactJSX and React

When working with Typescript and React, it's necessary to specify the jsx option in the compilerOptions section of the tsconfig.json file. Available values for this option include preserve, react, react-native, and react-jsx. { "compilerOptions": { ...

Inform TypeScript about functions that are dynamically defined

I am implementing a unique class structure as shown below: class App<objectList extends {}> { private objects: Map<keyof objectList, any> = new Map(); add<T extends keyof objectList>(name: T, type: objectList[T]) { this.obj ...

Discovering the process of extracting information from an individual object within a local JSON file on a detailed page using Angular 9

Here is a JSON object I am working with: [ { "products": [ { "id": "1", "name": "Apple", "price": "free", "imageURL": "assets/apples.jpg", "category": "Fruits" }, an ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

Potential undefined objects in Angular unit testing

While working on unit testing, I encountered the following error: 'Object is possibly 'undefined'' it('should set the dataSource filter to the provided argument', () => { component.applyFilter('filterValue') ...