Retrieving information from the GitHub API using Angular 4

I attempted to retrieve my last commit from GitHub using the GitHub API, but encountered an error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

I was able to fetch data from a simple JSON file and used a service with code similar to the following. However, now it's not working for me. Link to JSON: JSON When I fetch data from this JSON, I don't encounter any errors and can display what I need.

This is my GitHub service:

import { Injectable } from '@angular/core';
import { Http, Response, HttpModule } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IpostsGithub } from './ipostsGithub'
@Injectable()
export class GithubService {

  private _postsURL = "https://api.github.com/repos/objectprogr/Dashboard/git/refs/heads/v1";


  constructor(private http: Http) {

  }

  getPosts(): Observable<IpostsGithub[]> {
      return this.http
          .get(this._postsURL)
          .map((response: Response) => {
              return <IpostsGithub[]>response.json();

          })     
  }

  private handleError(error: Response) {
      return Observable.throw(error.statusText);
  }

}

GitHub component:

import { Component, OnInit } from '@angular/core';
import { GithubService } from './github.service';
import { IpostsGithub } from './ipostsGithub';

@Component({
  selector: 'app-github',
  templateUrl: './github.component.html',
  styleUrls: ['./github.component.css'],
  providers: [ GithubService]
})
export class GithubComponent implements OnInit {

  _postsArray: IpostsGithub[];
  user: string;
  constructor(private githubService: GithubService, ) {
  }
  getPost(): void {
    this.githubService.getPosts()
        .subscribe(
            resultArray => this._postsArray= resultArray,
            error => console.log("Error :: " + error)
        )
}


ngOnInit(): void {
    this.getPost();
}
}

And HTML:

<table class="table">
  <thead>
    <th>1</th>
  </thead>
  <tbody>
    <tr *ngFor="let post of _postsArray">
      <td>{{post.message}}</td>
    </tr>
  </tbody>
</table>

This is the error code that appears in the browser console:

_postsArray: […]
0: {…}
object: {…}
sha: "f0814bea75841ef7488552d29c6e1b8ad849f558"
type: "commit"
url: "https://api.github.com/repos/objectprogr/Dashboard/git/commits/f0814bea75841ef7488552d29c6e1b8ad849f558"
__proto__: Object { … }
ref: "refs/heads/v1"
url: "https://api.github.com/repos/objectprogr/Dashboard/git/refs/heads/v1" 

Any ideas on how to fix this issue?

Answer №1

It appears that the API is delivering a collection of objects, however ngFor can only iterate over arrays and not objects.

Answer №2

It appears that you are dealing with an Object instead of an Array and need to iterate over it. Please correct me if I'm mistaken.

If this is the scenario, here's how you can approach it:

In your .ts file

    export class SomeClass {
    Object: Object;
    constructor() {
     ...
    }
}

In your .html

<div *ngFor="let item of Object.keys(yourObject); let i = index;">
    {{item}}={{yourObject[item]}}
</div>

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

What is the best way to handle and work with the JSON response from Twitter's API?

I am currently working with the Twitter API (version 1.1) in PHP and trying to extract a specific variable from the JSON response. The $mentions variable represents the result of parsing JSON data returned by a GET statuses/mentions_timeline request. Here ...

I'm currently working on building a fresh window with Tauri 1.2, combining the powers of Rust, React, and Typescript. However, I've encountered a few

Utilizing Tauri's WindowBuilder in Rust, I attempted to create a new window. Despite successfully generating a blank window, I encountered challenges: The inability to display any content on the window The failure to close the window Being relativel ...

Issue with Microsoft Azure and AngularJS: Chart not rendering data as expected

I've encountered an issue where I can view the data locally, but once I open the Windows Azure cloud service application, the Json data is no longer being passed into my chart (). The Console displays a message stating "Controller names should start w ...

What causes the error message "No exported member 'ɵɵFactoryDeclaration' in @angular/core/core" to appear during project compilation?

I am facing an issue where the global Angular CLI version is 13.0.1 and the local version in my project is 10.2.3. Despite making changes to some components (without touching package.json), I encountered an error during the build step of my bitbucket pipel ...

Adding an array to JSON using PHP

I have extracted a group of IP addresses from a database and I need to embed them into a JSON object as an array. Below is the JSON structure: $jsonString="{ \"id\": 1, \"type\": \"service\", \"n ...

Check if the Datatable is empty using an alert

Working with Datatable V. 1.10.12, the data is successfully rendered using PHP/Ajax/JSON. Recently, I added some buttons, including a delete button outside the table to remove selected rows. Everything works fine, except for when the table is empty and the ...

Tips for rendering JSON text on a Java Canvas

Is there a way to display a nicely formatted JSON object/string on an Android Canvas? Here's an example: val jsonText = "{"profile":{"name": "Robert","account_id": "31"}}" This JSON string will be rendered on a Canvas like this: https://i.sstatic. ...

An error message occurs in TypeScript when trying to access a property that does not exist in an array

I'm having trouble figuring out this issue... I am receiving data from an API and storing it as an array. I'm attempting to access the data in this format... this.data.results[i].datas[j].dataType However, I keep getting the error "property res ...

Launch a TypeScript Node.js server on Heroku deployment platform

I'm having trouble deploying a Node.js server built with TypeScript on Heroku. Despite following various tutorials and searching through Stack Overflow for solutions, I can't seem to make it work. Here is the code I have in my tsconfig.json and p ...

What is preventing me from returning a JSON object in Perl script?

I am currently working on a project that incorporates jQuery, AJAX, JSON, and Perl. To handle the backend operations, I am utilizing Perl along with its CGI module to generate a JSON object. #!/usr/software/bin/perl5.8.8 use strict; use warnings; use CGI ...

A more efficient method for querying documents based on ids that are not in a given list and then sorting them by a specific publish date

After implementing the code provided below, I noticed that the performance tests indicate each request takes a second or longer to complete. My goal is to enhance this speed by at least 10 times. The bottleneck seems to be caused by the NOT operator resu ...

Troubleshooting issues with redirecting from http to https in Angular and Apache

After installing an SSL cert, my goal is to redirect all traffic from http to https. I have made the necessary changes to my Apache server: IncludeOptional conf.d/*.conf <VirtualHost *:80> ServerName www.memoriesgameseries.com Redirect "/" " ...

Tips for retrieving the present value of a piped/converted BehaviorSubject

How do I retrieve the current value of the observable generated by readValue() below without subscribing to it? var subject = new BehaviorSubject<Object>({}); observe(): Observable<Object> { return subject.pipe(map(mappingfunction)); } Do ...

Implementing data binding for arrays of inputs in Angular

Can anyone provide assistance with this code snippet and explain why it is not functioning as expected? I am trying to generate input fields from a string array and bind each input value to its corresponding element in the array. It seems like a common tas ...

Creating dynamic connections between Plain Old Java Objects (POJOs) and RESTful APIs through automated

I have a POJO class that requires me to access a RESTful web service using specific properties from the POJO as parameters. The challenge lies in not knowing the endpoint and its parameters until runtime. Essentially, the user will set up the endpoint, i ...

Tips for retrieving and storing an HTTP Post response in Angular 4 using HTML formatting

I am currently facing a challenge in Angular 4 where I am trying to retrieve and read the HTTP Post response. However, I am unable to do so because the response is in HTML format. Despite my efforts of researching various sources, I have not been able to f ...

Error: Tried to modify a property that is read-only while using the useRef() hook in React Native with Typescript

https://i.sstatic.net/jhhAN.pngI'm facing an issue while attempting to utilize a useRef hook for a scrollview and pan gesture handler to share a common ref. Upon initializing the useRef() hook and passing it to both components, I encounter an error th ...

Styles in print CSS are not effective in an Angular project

Currently, I am working on an Angular project where I need to generate a printable document using CSS. The challenge I am facing is ensuring that the date and title in the header do not print automatically when the document spans multiple pages. Additional ...

Using Typescript to retrieve the Return Type of a function when called with specific Parameter types

My goal is to create 2 interfaces for accessing the database: dao can be used by both admins and regular users, so each function needs an isAdmin:boolean parameter (e.g. updateUser(isAdmin: boolean, returnUser)) daoAsAdmin, on the other hand, allows metho ...

Difference between an optional field and a null value in kotlinx.serialization

Is there a way to differentiate between handling {data: null} and {} when parsing JSON using kotlinx.serialization? @Serializable class MyClass(val data: String?) ...