Struggling to retrieve API data in Angular 6

I am facing an issue with my code where the Get request is unable to fetch api values for posts, although it was successful for users. The code is simple, but I can't seem to figure out why it fails for posts.

Here is my posts.components.ts file:

import { Component, OnInit } from '@angular/core';

import {DataService} from '../data.service';
import {Observable} from 'rxjs';


@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
  posts$: Object;

  constructor(private pdata: DataService) {
   }

  ngOnInit() {
      this.pdata.getPosts().subscribe(
        pdata => this.posts$ = pdata
      )

      console.log(this.posts$);
  }

}

This is the html file:

<h1>Posts</h1>
<ul>
  <li *ngFor = "let pst of post$">
    <a routerLink=""> {{post$.title}}</a>
    <p>{{post$.body}}</p>
  </li>
</ul>

And this is my service file:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';


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

  constructor(private http: HttpClient) { }
  getUsers(){
    return this.http.get('https://jsonplaceholder.typicode.com/users')
  }
  getUser(userid){
    return this.http.get('https://jsonplaceholder.typicode.com/users/'+userid)
  }
  getPosts(){
    return this.http.get('https://jsonplaceholder.typicode.com/posts');
  }
}

Upon checking the console, it shows undefined and on the html page only the header is visible without any data. What steps should I take to resolve this issue?

Answer №1

In the initial code snippet, logging was being done outside of the subscribe function before the data was fetched from the API. To correct this, update the code as shown below:

ngOnInit() {
  this.pdata.getPosts().subscribe(
    pdata => {
      this.posts$ = pdata
      console.log(this.posts$);
    } 
  )
}

Additionally, there were issues in the HTML where 'post$' was being used instead of 'posts$', and there were some typos in the code. Make the following changes to resolve these errors:

<h1>Posts</h1>
<ul *ngIf="posts$.length > 0">
  <li  *ngFor = "let post of posts$">
    <a routerLink=""> {{post.title}}</a>
    <p>{{post.body}}</p>
  </li>
</ul>

Answer №2

Ensure that the console.log statement is placed inside the subscribe function in ngOnInit.

 ngOnInit() {
      this.data.fetchData().subscribe(
        data => {
          this.dataArray = data;
          console.log(this.dataArray);
        });    
  }

If you need to access the variable in the component, consider using *ngIf or the safe navigation operator because the request is asynchronous.

 <a routerLink=""> {{data$?.info}}</a>
    <p>{{data$?.description}}</p>

Answer №3

Big thank you to everyone who provided answers and assistance, but I managed to resolve the issue on my own. The variable name 'posts$' was not the problem, as I am simply using it as a variable placeholder.

The actual issue was located here:

 ngOnInit() {
      this.pdata.getPosts().subscribe(
        pdata => this.posts$ = pdata

Instead of pdata => this.posts$ = pdata, it should have been data => this.posts$ = data. This change was necessary because the method is being called from a specific DataService module I created. Using 'pdata' caused the module to not be recognized, resulting in no data displaying in the HTML file. Thankfully, everything is now working smoothly.

Answer №4

Ensure your HTML file is structured as follows:

<h1>Blog Posts</h1>
<ul>
  <li *ngFor="let post of posts$">
    <a routerLink=""> {{post.title}}</a>
    <p>{{post.body}}</p>
  </li>
</ul>

Remember to include the console.log statement within your API call function like this:

ngOnInit() {
    this.blogService.getPosts().subscribe(
      responseData => { 
          this.posts$ = responseData;
          console.log(this.posts$);
      }
    )  
}

While this may not directly address the main issue, it can assist in pinpointing the root problem. Give it a try and let me know how it goes so we can troubleshoot further!

Answer №5

Make sure to correct this post: the posts should be an array of any type

 posts$: any[];

It's recommended to initialize it with an empty array like this:

 posts$: any[] = [];

To check the value of the result (pdata), move the console.log statement to the subscribe callback function or inspect the network panel in the Chrome developer tools:

ngOnInit() {
      this.pdata.getPosts().subscribe(pdata => {
           this.posts$ = pdata;
           console.log(this.posts$);
  });  
}

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 in Vuetify 3.1.2 with Vue 3 and TypeScript: Unable to assign type 'boolean' to type 'never'

I am currently building a project using Vue 3 (version 3.2.45), Typescript (version 4.9.4), and Vuetify (version 3.1.2). When working with Vuetify components, I often encounter situations where I need to pass specific props for styling, positioning, or ma ...

Stop receiving updates from an Observable generated by the of method

After I finish creating an observable, I make sure to unsubscribe from it immediately. const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => { console.log('live', res); data$.unsubscr ...

Encountering an undisclosed CORS error on all requests from Angular frontend to NodeJS Express Server during preflight 200

After thorough testing with Postman, my backend server is functioning properly and generating the desired responses for all requests. However, my Angular app is encountering an unknown CORS error on every request despite receiving a 200 Preflight response ...

Tips for importing a library in a TypeScript file that expands a JavaScript prototype

After following the instructions provided in this question, I am experimenting with integrating Moment.js to enhance the capabilities of the Date prototype within a TypeScript project. The process of extending the Date prototype appears successful, as out ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...

Active Angular component utilizing *ngIf during the programmatically lazy loading of a Module

I find myself in a situation where I need to load numerous components on a specific route within my application. These components are controlled by a logic with *ngIf directives that allow me to show or hide them dynamically. For instance: <div *ngIf=& ...

Running headless Chrome with Protractor on Windows platform is presenting difficulties

While there is a wealth of documentation available on headless chrome automated testing, information specifically for Windows users seems to be lacking. Furthermore, details on utilizing headless chrome for end-to-end automated testing in a fully develope ...

How should I properly initialize my numeric variable in Vue.js 3?

Encountering an issue with Vue 3 where the error message reads: Type 'null' is not assignable to type 'number'. The problematic code snippet looks like this: interface ComponentState { heroSelected: number; } export default define ...

The inclusion of routes from an API request in Angular does not seem to be functioning properly when

Currently, I am embarking on a project that requires the loading of specific routes from a CMS using an API request. Upon executing the code snippet below with "ng serve -o," all routes function properly; however, once I run "npm serve:ssr" following a bu ...

Angular component displaying 'loading' message during API request in child component

My Dashboard component fetches data from different API's and sends it as @Input() marketData to an Infobox container to display the information. I want to display a loading symbol while waiting for the data to load. I attempted to use an *ngIf else ...

Is there a solution available for the error message that reads: "TypeError: Cannot set value to a read-only property 'map' of object '#<QueryCursor>'"?

Everything was running smoothly in my local environment, but once I deployed it on a Digital Ocean Kubernetes server, an error popped up. Any assistance would be greatly appreciated. https://i.stack.imgur.com/VxIXr.png ...

Error: Cannot modify the constant property 'name' of the function."&squo;

As I attempted to enter text into the input box, an error message appeared after typing my first letter stating "cannot assign to read only property". Below is the code I am referring to: The code of the component can be found here: https://i.sstatic.net ...

Properties of untyped objects in TypeScript are not defined

Here is the code snippet I've been working on: file.js const channel = {}, arr = [string,string,string]; for(let i = 0;i < arr.length;i++ ){ channel[arr[i]] = "Amo" //equal string value } I have an array that contains only string values, for ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as sh ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

An issue was encountered in the node_modules folder while attempting to access the 'Exclude' name in the lodash collection file. The error message reads: (1783,24): error TS2304: Cannot

When attempting to execute the ng serve command, I encountered an error. See below for more details. ERROR in node_modules/@types/lodash/common/collection.d.ts(1783,24): error TS2304: Cannot find name 'Exclude'. ... (error list continued) .. ...

The Angular 13 interceptor is not capturing a 403 error as expected

When it comes to running a .NET 6 API, the Angular 13 application is encountering an issue with intercepting a 403 error. Strangely enough, the 401 error is being handled properly. The problem lies in the fact that the 403 error does not trigger the (err: ...

Data sent from Angular does not reach the C# controller it is intended for

I am currently facing an issue with my Angular component method that is intended to send data to a C# Controller. Despite successfully retrieving data from the controller to Angular, I encounter a problem when attempting to send data back to the controller ...