Why isn't my data appearing when using $http.get in AngularJS?

I'm encountering an issue where my bar graph doesn't display data when using $http.get. However, if I eliminate $http.get and directly call the URL, the data shows up perfectly. Any suggestions on what might be causing this problem?

AngularJS

var app = angular.module('customCharts', ['dx']);

function ChartController($scope, $http) {

    $http.get("http://localhost:53640/Home/PostChart")
        .success(function (data) {
            $scope.productSettings = {
                dataSource: data,
                title: 'Displays Product Costs for items in our Database',
                series: {
                    argumentField: "Name",
                    valueField: "Cost",
                    type: "bar",
                    color: '#008B8B'
                },
                commonAxisSettings: {
                    visible: true,
                    color: 'black',
                    width: 2
                },
                argumentAxis: {
                    title: 'Items in Product Store Database'
                },
                valueAxis: {
                    title: 'Dollar Amount',
                    valueFormat: 'currency'
                }
            };
        });

}

HTML

<div ng-app="customCharts">
    <div ng-controller="ChartController">
        <div dx-chart="productSettings"></div>
    </div>
</div>

JSON

[{"Name":"Learn SQL Server 2014","Cost":34.95},{"Name":"ASUS PC","Cost":499.99},{"Name":"SQL Server 2014","Cost":600.00}]

Answer №1

Here is my approach to resolving this particular issue.

let app = angular.module('customCharts', ['dx']);

app.controller("ChartController", function ($scope, $http, $q) {
    $scope.productSettings = {
        dataSource: new DevExpress.data.DataSource({
            load: function () {
                let def = $.Deferred();
                $http({
                    method: 'GET',
                    url: 'http://example.com/Home/GetData'
                }).success(function (data) {
                    def.resolve(data);
                });
                return def.promise();
            }
        }),
        series: {
            title: 'Visualizing Product Prices for our Database Items',
            argumentType: String,
            argumentField: "Name",
            valueField: "Price",
            type: "bar",
            color: '#FFA500'
        },
        commonAxisSettings: {
            visible: true,
            color: 'blue',
            width: 2
        },
        argumentAxis: {
            title: 'Products in the Database'
        },
        valueAxis: {
            title: 'Amount in Dollars',
            valueFormat: 'currency'
        }
    }
})

Answer №2

To ensure the chart updates correctly, it is important to implement two-way binding. Include the following code within your $scope.productSettings:

    $scope.productSettings = {
       ...
       bindingOptions: {
         dataSource: 'dataSource'
       }
    };

In this code snippet, the attribute dataSource refers to a variable in your scope ($scope.dataSource) that you will need to update after successfully executing the $http.get method.

    $http.get('http://localhost:53640/Home/PostChart').
    success(function(data) {
       $scope.dataSource = data;
    });

For more information, refer to the documentation here

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

Using jQuery within an Angular Controller: The specific function $(...).overhang is not recognized in this context

Recently, I decided to integrate overhang.js into my application because of its appealing alert messages. Initially, it seemed like a simple task... All I needed to do (or so I thought) was replace the line in my controller, alert("An HTTP request has be ...

Fetching a value by key from a JSON object in a Node.js script

How can I extract the id value from this JSON object? answerTag: [ '[{"id":64,"name":"Coronary Artery Disease"}]', '[{"id":64,"name":"Coronary Artery Disease"}]' ], risk: '1' } ...

Creating dropdown options with JSON and Angular

This dilemma has been causing me no end of distress. I am trying to figure out how to populate options for a select tag from a JSON object using Angular. Here is a snippet of the code: <select id="cargo" ng-model="cargo.values.cargoList"> <op ...

Finding the root cause of the error message 'Unexpected character: :' from using rjson

My company recently acquired a JSON data set, and I need to extract specific information from it. However, when attempting to import the data using the "fromJSON" method, I encountered an error as described in the title. With over 16,000 files worth of d ...

Deciphering JSON information using a LOOP

I'm having trouble parsing data from JSON using UNION ALL because I need to repeat the process multiple times. I tried using a LOOP but it didn't work as expected. My goal is to parse each element from an array in JSON into rows for statements. ...

Guide on utilizing JSON data sent through Express res.render in a public JavaScript file

Thank you in advance for your assistance. I have a question that has been on my mind and it seems quite straightforward. When making an app.get request, I am fetching data from an external API using Express, and then sending both the JSON data and a Jade ...

Pressing the element may result in some instability in its operation

$scope.triggerUpload = function(){ $timeout(function() { angular.element('#upload').trigger('click'); }, 100); }; Everything works smoothly when triggering the upload function three times, but on the fou ...

Maintain the current states when returning to a previous point in time

In my Angular app, I have multiple pages that allow users to make changes such as opening tabs and pills, modals, etc. For instance, if a user opens a modal and then clicks a link within that modal that takes them to another page, I want the original page ...

Decoding a collection of items using Jackson

I need to parse a list of objects using Jackson. While it's easy with Gson: List<MyType> list = new Gson().fromJson(input, Types.listOf(MyType.class)); It seems more challenging with Jackson: List<MyType> list = new ObjectMapper().readV ...

Angularjs update the <select> tag inside ng-if functionality

Looking for help to update the list of states based on the selected country. I've tried using $parent as recommended, but it's not working for me. Can someone guide me on how to populate the state select control? Also curious about handling mult ...

Having difficulty invoking another controller within a controller in Angular by utilizing $rootScope, $compile, and $route

mainApp .controller('homeController', function($scope, $http, $timeout, $compile, $rootScope, $routeParams, $location, $route) { //implement functionality here } ); mainApp.controller('ReportsController', function($sc ...

Remove the image by clicking on the "X" icon located on the top right corner of the image

One of my tasks involves deleting an image by clicking on the "X" mark located at the top right corner of the image. To achieve this, I referred to this CSS fiddle http://jsfiddle.net/yHNEv/. Sample HTML code: <div class="img-wrap"> <span ng-c ...

Manipulating JSON Data with Retrofit on Android

I've successfully retrieved a JSON response using OkHttp3, and now I'm trying to utilize Retrofit to parse the response in order to extract the name and image from it. Despite looking through the Retrofit website and various tutorials, I still fi ...

Angular appends a slash to the URL path index.php#/todiv preventing me from navigating to the desired location

This situation occurs almost always. AngularJS is inserting a slash in index.php#/gohere, causing me to be unable to access "gohere". Why does Angular put the slash, and how can I stop it from adding the slash between index.php#/gohere? It should normall ...

By harnessing a JSON response

After sending an ajax request, the server's response is as follows: {"error":false,"success":true} The ajax code used: $.ajax({ url: '/update', type: 'post', data: $(this).serialize(), success: function(response) ...

Tips on parsing JSON data with Python

I am currently working with a module that provides data in the following format: j = ("{u'auth_user': {u'first_name': u'a', u'last_name': u'b', u'uid': u'x', u'timezone_offset&apos ...

convert a JSON object into an array field

I am looking to convert a list of objects with the following structure: { "idActivite": 1, "nomActivite": "Accueil des participants autour d’un café viennoiseries", "descriptionActivite": "", "lieuActivite": "", "typeActivite": "", ...

Definition of JSON Schema attribute: Field schema not supported for field... : Type of field is undefined

I am in the process of creating a form that is based on a JSON schema and utilizing the react-jsonschema-form component for ReactJS. The purpose of this form is to allow users to input various settings (such as CSS/HTML selectors) that will be used to ext ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

In the absence of an Avatar, verify the gender from the JSON data and insert it into the image

I have created my very first app where users can upload their avatars and set their gender. If a user (in this case, a girl) does not upload an avatar, I want to check the JSON data for their gender information. Based on this gender information, I want to ...