Why does $http.get succeed but I can't retrieve the output?

How can I retrieve the output from my remote server? - After verifying with Firebug, it seems that the JSON output is correct.

Below is my approach, aiming for standardization (Plnkr):

app.js, controllers.js, factories.js

'use strict';

var nameVersionFactory = angular.module('name.factories.version', []);

nameVersionFactory.factory('Version', ['$q', '$http', function ($q, $http) {
    var d = $q.defer();
    $http.get('/api').then(function (response) {
        d.resolve(response);
    });

    return d.promise;
}]);

var nameVerCtrl = angular.module('name.controllers.version',
                                 ['name.factories.version']);

nameVerCtrl.controller(
    'verCtrl', ['$scope', 'Version', function ($scope, Version) {
        $scope.version = Version;  /* {'status': 'online',
                                       'rest_api_version': '1.1.14',
                                       'server_time': '…'} */
    }]
);

var nameApp = angular.module('name', ['name.controllers.version']);

/* CORS */
nameApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

Python REST API (30 lines): https://gist.github.com/anonymous/7d34867aca543911a06f

index.html

<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="name" lang="en">
    <head>
        <meta charset="utf-8">
    </head>

    <body>
        <div data-ng-controller="verCtrl">
            <pre>{{version | json}}</pre>
            <pre>{{version.status}}</pre>
            <pre>{{version.data | json}}</pre>
            <pre>{{version.data.status}}</pre>
        </div>

        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js">
        </script>
        <script src="scripts/controllers.js"></script>
        <script src="scripts/factories.js"></script>
        <script src="scripts/app.js"></script>
    </body>
</html>

Unfortunately, I am not seeing any JSON output within the specified <pre>…</pre> tags.

Answer №1

In Angular 1.2+, scope variables no longer automatically unwrap promises.

Therefore, you need to write:

Version().then(function(result){
    $scope.version = result;    
});

Furthermore, $http already returns promises, so instead of:

var d = $q.defer();
$http.get('/api').then(function (response) {
    d.resolve(response);
});

return d.promise;

You can simply use:

return $http.get("/api");

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

React/React Hooks: Want to initiate input validation when a user deselects a checkbox

Currently, my component includes an input field and a checkbox. When the checkbox is checked, it disables the input field and clears any validation errors. However, I want to add functionality so that if the checkbox is unchecked, the input field becomes ...

The current status of an ASP.Net Mvc Ajax request

Currently, I am utilizing @Ajax.ActionLink to invoke a controller action in an ajax manner. Is there a method to identify if there is already an ongoing/pending ajax request on the page? The desired functionality is simple: when a user clicks the link, the ...

From JSON array to object class

Here is the JSON array response I am dealing with: [ { "status": "active", "url": "https:\/\/ikiosk.podio.com\/dev\/apps\/myusers", "url_label": "myusers", "space_id": 550628, "link_add": "https:\/&b ...

JavaScript error: Undefined variable or function

I'm facing an issue with the following code. When I position the brace in different places, I encounter errors like "var not defined" or "function not defined". My goal is to convert an array into a string so that I can analyze the data and decide how ...

Screen the $http request information prior to transmission

Angular has a built-in feature that removes properties with a prefix of $$ from request data or params objects. I want to filter out my own UI-specific properties that I don't want to send to the server, but I don't want to rely on using $$. Is ...

Tips for modifying the JSON format within a Spring and Angular project

I am utilizing Spring for the backend and Angular for the frontend. Below is my REST code: @GetMapping(path = "/endpoint") public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) { return ...

Using Leaflet JS to add custom external controls to your map

Is there a way to implement external controls for zooming in on an image? I've searched through the documentation, but haven't been able to find a clear solution. HTML: <div id="image-map"></div> <button id="plus">+</butto ...

Reduce the text of the link

Trying to simplify a task, but I'm struggling with the solution. What I want to achieve is shortening a link to 30 characters and adding ... at the end if it's longer. Also, I'd like to make it possible to see the full link on hover similar ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...

The JSON API is designed to return an array containing only a single result

I am currently developing an API that provides information based on a given address. Some of the data in our tables contain duplicates, but with over 15 million entries, manually identifying and removing duplicates is not feasible. As a solution, I have ch ...

Injecting Ajax-loaded content into an HTML modal

Hey there! I'm currently working on a project involving the IMDb API. The idea is that when you click on a film title, a popup should appear with some details about the movie. I've made some progress, but I'm stuck on how to transfer the mov ...

Alias destructuring for arrays within nested objects

I'm currently attempting to change the names of certain objects from one array (eventFetch) and transfer them into another array (mapEvents). I initially tried using destructuring aliases for this task, but since I need to rename a nested object, it d ...

Is compiling inline sass possible with npm?

Looking for a simple method to achieve this task? I've experimented with sass, node-sass, and tinysass without success. My goal is to compile inline sass in JavaScript, much like the code snippet below: import sassPkg from 'sass-pkg' const ...

JQuery Falters in Responding to Button's Click Action

Forgive me for what may seem like a silly question, but as someone new to JQuery, I have been struggling to figure out why my function is not displaying an alert when the button is clicked. Despite thorough research on Google, I haven't been able to f ...

Determine the dimensions of Expo's React Native Over the Air (OTA) update

Is there a method to determine the size of the required download for an OTA update before existing deployed apps (e.g. v1) retrieve it following the publication of a new managed Expo app (e.g. v2)? ...

Dynamic matching of variables being passed to a directive

My latest coding project involved creating a custom directive for managing HTML images, making it easier to store and display URLs and alt tags. By using a specific value via the data field (referred to as data-type in the code), I can effortlessly replace ...

Issues arising from using THREE.js canvasTexture

Describing my current issue. I have generated a Terrain geometry using a DEM. I am now downloading OSM Tiles to use as textures for this geometry. Every time a new Tile is downloaded, the callback function processMapImage is triggered: function processMa ...

The Vue pagination component is optimized to load a single page at a time

There seems to be an issue with my paginate component as it is only displaying the first page despite the total number of objects I want to show: https://i.sstatic.net/rEonp8Rk.png Pagination Component Code: <paginate v-if="searchResults.length & ...

Using React-Router-Config to dynamically set the page title

I am seeking advice on how to dynamically set page titles using the configuration file in conjunction with react-router-config. Should I use props or Helmet for this purpose? routes.js const routes = [ { title: 'Home', path: ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...