Angular method $http.get is failing to function as intended

This is the HTML and JavaScript code I have written.

<!DOCTYPE html>
<html ng-app>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="js/angular.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-controller="MainController">
    Name: {{user.login}}   
</body>
</html>

Here is my JavaScript function for MainController.

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

    $http.get("https://api.github.com/users/sfshameem5")
    .then(onUserComplete);

    $scope.message = "Hello, Angular!";
}

I am hoping to display the user's login name with {{user.login}}, but it's not showing up as expected.

Answer №1

Try this solution for your code: Instead of:

$scope.user = response;

Use:

$scope.user = response.data;

The following code snippet is currently operational.

Here is the HTML:

<!DOCTYPE html>
    <html ng-app="app">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
            <script src="https://code.angularjs.org/angular-1.0.1.js"></script>
    </head>
    <body ng-controller="MainController">
        Name: {{user.login}}
    </body>
    </html>

And for your JavaScript file:

var app = angular.module('app', []);
app.controller('MainController', function($scope, $http) {
    $http({
        method: "GET",
        url: "https://api.github.com/users/sfshameem5",
    })
            .success(function(response) {
                $scope.user = response;
             })
            .error(function(response) {
                console.log("Failed fetching data:" + response);
            });
});

Answer №2

Utilizing $http's GET method

$http({
   method:"get",
   url:"https://api.github.com/users/sfshameem5"
   }).success(function(response){
      $scope.user=response.data
   }).error(function(err){
      console.log(err)
   })

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

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

Utilize the JavaScript .send function to pass an array

Can an array be passed to a PHP page using the code below? If not, what modifications are needed in the code? function ajax_post(){ var hr = new XMLHttpRequest(); hr.open("POST", "get_numbers.php", true); hr.setRequestHeader("Content-type", "a ...

Shader customization and dynamic window resizing with Three.js

Having trouble with resizing the Three.js shader scene using ThreeX to handle window resizing and changing orientation on mobile devices. When the window width is decreased, everything works perfectly. However, expanding the window either in width or heigh ...

What is the reason that the 400 status code consistently causes the enter catch block to execute when using axios?

In the frontend of my website, there is a contact form with three fields -> name, email, message. These fields are then sent to the backend using Axios. If a user fails to fill out any of the required fields, they should see a message saying "please f ...

Organize your file dependencies efficiently using NPM

I'm currently part of a medium-sized team working on a large front-end application. Up until now, we have been using requirejs and AMD modules to manage our project with approximately 500 files. However, we recently decided to transition to commonjs a ...

A simple way to initiate an AJAX call once the page has completed loading is by using the `window.location.href` as the

I encountered an issue with my event listener setup function navBtn() { $('#navBtn').on('click', (event) => { window.location.href = 'someotherfile.html'; myAJAXrequest(); }) } The problem I'm facing is that ...

Utilizing modals for form validation in Angular

Having trouble implementing form validation within a modal pop up? Read on for some guidance. In my view, here is an example of how the form is structured: <script type="text/ng-template", id="modalVideoNew"> <div class="ngdialog-message"> ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

`Stop the JW Player from playing several videos simultaneously`

I have a situation where I want to display multiple videos on the same page, but only one should be playable at a time. When a new video is started, the currently playing video should automatically stop. <div class="tab-pane active" id="abc"><d ...

Check the dimensions of the image file entered using AngularJS on the client side

Before uploading an image to the server, I need to validate its dimensions on the client side. I have searched for solutions using img.Onload(), but that's not what I am looking for. All I want is for the user to choose the image from <input ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Running a JavaScript asynchronous function and capturing the output using Selenium

Attempting to run the script below in Selenium result = driver.execute_script('let result; await axe.run().then((r)=> {result=r}); return result;') Results in an error: Javascript error: await is only valid in async function Another at ...

Animated the height of a rectangle during initial loading and when the mouse hovers over or leaves

Being new to Vue.js, I am looking to create a simple animation on component load for the first time. You can find my initial code here: <template> <div id="app"> <div class="rect" /> </div> </template ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...

Enhance your website with the jQuery autocomplete feature, complete with

Is there a way to incorporate smaller text descriptions alongside the search results displayed on my website? The descriptions are available in the data array used by autocomplete and can be accessed using the .result function by calling item.description. ...

Stop JavaScript Injection Attacks

Let's consider a scenario where a user inputs information into a form that is then submitted to the server using PHP. In the PHP code, we have: $data = $_POST['data']; // or $data = strip_tags(@$_POST['data']); I am curious t ...

Angular JS application failing to load in browser due to a simple issue

I recently completed working on two pages index.html and app.js, which were created while following a helpful tutorial found here. The structure and content of each page are outlined below: index.html <!DOCTYPE html> <html ng-app ="store"> ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

Intranet User Interface Developed with AngularJS

When utilizing ASP.Net Web API service, I am able to retrieve the current Windows user using the code snippet below. public class UserController : ApiController { public string Get() { var id = WindowsIdentity.GetCurrent(); retu ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...