Learning to interpret JSON data retrieved from a RESTful API with Angular

Currently delving into the basics of Angular, I have embarked on a small project. Utilizing JSONPlaceholder, a fake REST API, my goal is to retrieve all posts and display them on a webpage through a straightforward ngFor loop. For this purpose, I have devised a service. I will showcase my code step by step. However, here is the corresponding stackblitz. I am seeking assistance with the following files:

  1. post-list
  2. post interface
  3. post.service

After diligently crafting this portion of the code based on articles and tutorial videos from platforms like Pluralsight and YouTube, I find myself at an impasse. Here is the excerpt of my code:

post.ts

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

post.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PostService {

  constructor() {}

  getAllPosts():Observable<Post[]> {
    return fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => console.log(json))
  }
}

post-list.component.ts

import { PostService } from './post.service';
import { Component } from '@angular/core';

import { Post } from './post'

@Component({
  templateUrl: './post-list.component.html',
})
export class PostList {

  posts: Post[] = [];
  errorMessage="";
  
  constructor(private postservice: PostService) {
    this.postservice.getAllPosts().subscribe({
      next: posts => {
        this.posts=posts;
      },
      error: err => this.errorMessage = err
    });
  }
}

I urge you to take a look at the stackblitz, as it can potentially save time and effort for everyone involved. My current obstacles are:

Can't bind to 'ngForOf' since it isn't a known property of 'div'. ("

Error: 0.9.1/dist/zone.j

Your guidance in pinpointing any mistakes and providing corrections would be greatly appreciated.

Answer №1

To improve your service, it is recommended to switch to using HttpClient within the context of HttpClientModule.

export class PostService {

  constructor(private httpClient: HttpClient) {};

  getAllPosts(): Observable<Post[]> {
    return this.httpClient.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
  }
}

Ensure that you properly import both HttpClientModule and CommonModule if you are utilizing child modules. Essential directives like async may not be accessible without importing them.

@NgModule({
  imports:[
    CommonModule,
    HttpClientModule,
   ...

There are multiple ways to retrieve and display your data, here are two main approaches:

Option 1

@Component({
  templateUrl: './post-list.component.html',
})
export class PostList {
  posts: Post[] = [];
  errorMessage: string;

  constructor(private postService: PostService) {}

  ngOnInit() {
    this.posts = this.postService.getAllPosts().subscribe(
      posts => {
        this.posts = posts
      },
      error => {
        this.errorMessage = error;
      }
    );
  }
}

Option 2 (preferred)

@Component({
  templateUrl: './post-list.component.html',
})
export class PostList {
  posts$: Observable<Post[]>;
  errorMessage: string;

  constructor(private postService: PostService) {}

  ngOnInit() {
    this.posts$ = this.postService.getAllPosts().pipe(
      catchError(error => {
        this.errorMessage = error;
      });
    );
  }
}

template.html :

<div *ngFor="let post of posts$ | async">
  <p>{{ post.userId }}</p>
  ...
</div>

Check out the updated stackblitz demo for this recommended option using Observable and async pipe.

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

Creating conditional keys using the Zod library based on the value of another key

Incorporating the TMDB API into my project, I am making an effort to enhance type safety by reinforcing some of the TypeScript concepts I am learning. To achieve this, I am utilizing Zod to define the structure of the data returned by the API. Upon invest ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

Can TypeScript provide a method for verifying infinite levels of nested arrays within a type?

Check out this example The concept behind this is having a type that can either be a single object or an array of objects. type SingleOrArray<T> = T | T[]; The structure in question looks like this: const area: ItemArea = [ { name: 'test1& ...

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

Preserving type information in TypeScript function return values

Wondering how to make this code work in TypeScript. Function tempA copies the value of x.a to x.temp and returns it, while function tempB does the same with x.b. However, when calling tempA, the compiler seems to forget about the existence of the b field ...

The problem within the nebular modules, such as 'nb-card' and 'nb-stripper', is causing issues

Struggling with using nebular in an Angular project - the nb-card component seems to be causing issues for me. Here is the error message I keep encountering. Any advice on how to resolve this? ERROR in src/app/kyc/documentverification/documentverification ...

Update not reflecting in Angular Reactive Form custom component value

I've developed a custom input component that extends the primeng spinner component. However, I'm facing an issue with Angular Reactive Form where the model value of my component is not being updated. To make it easier to debug, I've created ...

The process of transitioning a fragment into a component

I am trying to dynamically change a fragment of the URL from within a component, but I am encountering difficulties in doing so. <a #linkComponent routerLink='home' fragment='part'>link</a> @ViewChild('linkComponent&a ...

Establishing a default value as undefined for a numeric data type in Typescript

I have a question regarding setting initial values and resetting number types in TypeScript. Initially, I had the following code snippet: interface FormPattern { id: string; name: string; email: string; age: number; } const AddUser = () => { ...

Retrieve unique values based on two or more criteria from an array in TypeScript

Presented here is an array. https://i.stack.imgur.com/zHXim.png The desired pattern is: https://i.stack.imgur.com/EGUiM.png I am interested in retrieving unique "CityRef" and "City". Subsequently, locating all items associated with them. ...

The infer keyword fails to provide the intended result due to the absence of a required property

Summary: interface CoreProps {prop1: number;} interface AnchorProps {prop2: number} type Feature<P extends object> = { state?: (state: object, props: P) => object | void; }; type FeaturePT<P extends object> = { state?: (state: object, props ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Tips for incorporating the observer design pattern in REST APIs (Communication between front-end and back-end)

Is it possible to subscribe once to an API and receive multiple responses until I unsubscribe from that event? If so, how can this be achieved? If not, why does this approach not align with the observer pattern's guidelines? I attempted using the yie ...

Activate the ion-navbar button when submitting from the modal page

import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import {ModalPage} from '../modal-page/modal-page'; @Component({ selector: 'page-page2', templateUrl: 'pa ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

Module '. ' or its corresponding type declarations cannot be located

While working on my project with TypeScript and using Cheerio, I encountered an issue when trying to compile it with TSC. The compiler threw the following exception: error TS2307: Cannot find module '.' or its corresponding type declarations. 2 ...

Apply rounded corners to the table row

Currently, I am utilizing a datagrid to display information. I have been attempting to implement border radius on all the table rows, but it doesn't seem to be working. Does anyone have insight into how I can apply border-radius to all rows in the t ...

Ensuring Input Validity in Angular4 and Symfony3

Currently, I am utilizing angular 4 and symfony3. In my application, there is a textarea that is required. However, when I only press enter (code 13) in this textarea without entering any other character, the form gets submitted. How can I prevent this spe ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

The error message "Uncaught ReferenceError: exports is not defined and require" indicates that

I am currently developing an app using angularjs and typescript, but I've encountered a persistent error that has me stumped. Below is the snippet of my code: export var NgApp = new application.Startup(); ///<reference path="../../../../../typin ...