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

Tips on creating a keypress function for a div element with the contenteditable attribute

Hey there, I have managed to create a textarea within a div by using -webkit-appearance. However, I am currently struggling to add an event to this div on key press. I have been trying my best to figure it out but seem to be missing something. If you coul ...

Is there a way to dynamically change the height in jQuery/JavaScript?

I am encountering an issue with my embed code where the height changes randomly after a few seconds, depending on certain parameters. Here is an example of the code I am using: $( <embed></embed>) .attr("src", "http://www.bbs.com") ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Utilizing Node.js ORM2 callback functions with custom parameters

Currently, I am developing models using a for loop: for (var j = 0; j < data.length; j++) { models.MyModel1.create({ name : data[j].name }, function(err, model){ if (err) { throw err } ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

An element generated through JavaScript fails to display on the webpage

As I navigate through the code with a foreach() loop, my goal is to generate a new div every time a firebase document containing the user's email is encountered. The script involves a blend of react js and javascript as I am still learning the ropes o ...

Activate an event on a separate webpage using jQuery or JavaScript

Currently, I am in the process of working on a project with 2 distinct pages: Index Settings On the Settings page, I have implemented a button to close an element and hide it. However, I am encountering an issue where I want the elements on the Index pa ...

I had hoped to remove just one item, but now the entire database is being erased

I present it in this way <tr v-for="(foodItem, index) in filteredFoodItems"> <td>{{ foodItem.name }}</td> <td>{{ foodItem.price | currency('£') }}</td> <td>{{ foodItem.category }}< ...

Comparing Chutzpah and Karma test runners: Understanding the distinctions

While researching test runners, I came across two options that confused me. Many people recommended Karma as the best choice, but both are essentially just runners for executing Jasmine code. What sets Karma apart? What are the specific differences betwe ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

Determine whether a component is linked to an event listener

If a <Form> component is called with a @cancel event listener attached to it, the cancel button that triggers this event should be visible. If no @cancel event is present, the cancel button should not be displayed. Is there a method to verify if a c ...

TRPC fails to respond to the passed configuration or variables (e.g., when enabled is set to false)

Recently started using trpc and I'm trying to grasp how to utilize useQuery (which I've previously worked with in react-query): const IndexPage = () => { const { isLoading, data, isIdle } = trpc.useQuery([ "subscriber.add", { email: ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

HTML5 on its own versus the dynamic duo of jQuery Mobile and AngularJS

We are in the process of creating a versatile mobile app that will work on multiple platforms using HTML5, JavaScript, and CSS. Our design approach includes utilizing Bootstrap for a responsive user interface, and Cordova to package the application for bot ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Transform the given text into components applicable to AngularJS

I have a dynamic dashboard with a JSON object that I populate with HTML elements in text format, like this: var items = [ {"id": "panel1", "description": "<div><a ui-sref='page1'>link a</a></div>"}, {"id": "panel2", "de ...

Utilizing query parameters as variables in rewrites with Next.js

My goal is to use Next JS to redirect requests from /home?id=123qwert to the new path of /home/123qwert. I'm struggling with extracting the query parameter from the source and using it in the destination. This is what I have attempted so far: as ...

Error message: When attempting to create dynamic inputs in React, an error occurs stating that instance.render is not

I encountered an issue while attempting to create dynamic inputs in React. The error message 'TypeError: instance.render is not a function' keeps popping up. import React, { Component } from 'react'; import Input from '../../Ui/Inp ...