"Angular fails to retrieve any data from JSON API, returning a blank response

My ng-repeat function is not returning anything, and as a beginner in Angular, I am struggling to identify the error. Despite thorough error checking, I can't seem to figure out what's going wrong here.

(function() {

  var app = angular.module("testApp", []);

  app.controller("MainController", function($scope, $http) {
   $scope.search = function(username) {
  $http.get("https://api.github.com/users/" + username)
    .then(onUserComplete, onError);

  $http.get($scope.user.repos)
    .then(onRepos, onReposError);
};

var onUserComplete = function(response) {
  $scope.user = response.data;
};

var onRepos = function(response) {
  $scope.repos = reponse.data;
};
  });

}());

Below is the HTML code where I intended to display the repositories of specific users on GitHub:

  <table>
    <thead>
      <tr>
       <th>Name</th>
       <th>Stars</th>
       <th>Language</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="repo in repos">
        <td>{{repo.name}}</td>
        <td>{{repo.stargazers_count }}</td>
        <td>{{repo.language}}</td>
      </tr>
    </tbody>
  </table>

Answer №1

The issue lies in the fact that the HTTP calls being made are asynchronous, meaning that when the second call is executed, the user data may not be available yet. To address this, you need to chain the promises together. If the user data is only needed for the second call, you can streamline your code like this:

$http.get("https://api.github.com/users/" + username)
     .then(function(response) {
         return $http.get(response.data.repos_url);
     })
     .then(function(response) {
         $scope.repos = response.data;
     }, 
     onError);

The first then is triggered upon the successful completion of the first get call, leading to the execution of the second get call. The second then is then executed upon the success of the second HTTP call, effectively chaining the promises.

I have provided a comprehensive example on JSFiddle for reference.

For the convenience of others, I am including the full code snippet below:

AngularJS

var myModule = angular.module('myModule', []);

myModule.controller('myController', ['$http', function ($http) {
    var $ctrl = this;
    $ctrl.username = null;
    $ctrl.repos = null;

    $ctrl.getRepositoryData = function () {   
        $ctrl.repos = null;
        $http.get('https://api.github.com/users/' + $ctrl.username)
             .then(function(response) {
                 return $http.get(response.data.repos_url);
             })
             .then(function(response) {
                 $ctrl.repos = response.data;
             }, 
             function (error) {
                 console.log('An error occurred:', error);
             });
    };
}]);

HTML

<div ng-app="myModule">
    <div ng-controller="myController as ctrl">
        <div>
            <input type="text" ng-model="ctrl.username"/>
            <button type="button" ng-click="ctrl.getRepositoryData()">
                Get Repos
            </button>
            <p>User repositories: {{ctrl.repos}}</p>
        </div>
   </div>
</div>

Answer №2

Make sure to include the following line of code inside the onUserComplete function: $http.get($scope.user.repos).then(onRepos, onReposError); . Keep in mind that Angular's http module methods are asynchronous, which means that after making a GET or POST call, Angular will move on to the next line of code without waiting for the response.

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

Implementing tooltips using JavaScript within Bootstrap 5

Is there a way to add both a tooltip and popover to the same element in Bootstrap v5 via Javascript? I have attempted to enable both of them using JS as it seems like the best approach. The tooltip that was added through html is functioning correctly: ...

Retrieve a pair of values in a Node.js JavaScript application

I'm in search of a solution to locate an item and its index within an array, and then store them in separate variables. Though I'm relatively new to programming, I'm encountering challenges in tackling this problem. I attempted to use destru ...

Is it possible to send two parameters to a JavaScript function using HTML?

Seeking help to develop an .html page where two string inputs are passed as parameters to a .js function, which then returns the longer of the two strings based on their lengths. Initially, I successfully created a functional .js script in VS CODE. Here i ...

Displaying queries using ajax in Rails

Can someone assist me in dealing with a particular issue? I am using ajax to refresh queries from the database dynamically each time there is a change in a search form. The main objective is to load N number of records based on the parameters selected in ...

Finding a JSON file within a subdirectory

I am trying to access a json file from the parent directory in a specific file setup: - files - commands - admin - ban.js <-- where I need the json data - command_info.json (Yes, this is for a discord.js bot) Within my ban.js file, I hav ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

Creating a large array of functions can be done by defining each function within the array individually, ensuring proper

I attempted to define an array of functions using the code below, but encountered issues with retrieving the value of 'i' outside of the loop. <script> var f = [] for (var i=0; i<1000; i++){ f[i] = function(){ return i } ...

Guide on effectively managing props within a single component in React Navigation

When attempting to navigate from my App component to the GamePlay component, I encountered an issue. Here is a snippet of my App.js: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; imp ...

Unable to download the jQuery Plugin

I am looking to install a gallery without using flash, and I came across this jQuery plugin called Grid-A-Licious. However, I am having trouble figuring out how to install and use it since it is distributed as a .zip archive with two .js files but no index ...

Is it just me, or does the this.router.subscribe method no longer exist in Angular 2's @angular/router library?

I'm experiencing an issue in Angular 2 with the library @angular/router. It appears that the method this.router.subscribe no longer exists. Previously, this code worked fine on an older version of the router that has since been deprecated. Does anyon ...

The initial loading of jQuery DataTables shows duplicate entries

Expanding on my query from the previous day: jQuery AJAX call function on timeout Following the guidance provided in the response from yesterday's post, the table successfully reloads without requiring a full page refresh every 30 seconds. However, ...

Applying custom styles to the initial 5 elements post clicking the button with Jquery

I have a set of HTML codes containing multiple buttons. <div class="main"> <div class="button hide">1</div> <div class="button hide">2</div> <div class="button hide">3</div> <div class="button h ...

Executing child processes in the Mean Stack environment involves utilizing the `child_process`

I am working on a Mean application that utilizes nodejs, angularjs and expressjs. In my setup, the server is called from the angular controller like this: Angular Controller.js $http.post('/sample', $scope.sample).then(function (response) ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...

Ways to align and fix a button within a specific div element

How can I make the button with position: fixed property only visible inside the second div and not remain fixed when scrolling to the first or last div? .one{ height:600px; width: 100%; background-color: re ...

Navigating through div elements using arrow keys in Vue

Trying to navigate through div elements using arrow keys is proving to be a challenge for me. I have successfully achieved it in JavaScript, but I am facing difficulties doing it the "vue way". Although there should be no differences, it simply does not wo ...

Insert DOM elements at the start of the parent element

I'm currently using the following JavaScript code to insert AJAX responses into a div with an ID of results: document.getElementById("results").innerHTML=xmlhttp.responseText; The issue I am encountering is that this code adds all new elements after ...

Reduxforms does not rely on preloaded CSS or JavaScript

Currently, I am utilizing MDBootstrap as my primary CSS framework and integrating redux forms to simplify form management. The issue at hand is that the design and style of elements appear different compared to the original static html page layout. Here ...

Update the parent node in the Google Org Chart

This is my first time working with Google Charts and I have a couple of questions: Is there a method in the API to update the parent of an existing node? I am facing a challenge where I need to build a tree structure top-down, which means that I know the ...

Converting JSON into HTML has me completely baffled

Despite my best efforts, I have managed to navigate my way through the code thus far, but I am puzzled as to why the JSON data is not being sent to the HTML via JavaScript. I can manually input the necessary parts in the developer console after onLoad an ...