Controller receiving incomprehensible response from service

Here is my service code:

'use strict';

    app
    .service('myService', function($http) {

        this.getJSON = function() {
            return $http.get('someUrl/dataForm').then(function(data){
                return data.result;
            });
        };
    });

In the controller, I am using the service as follows:

'use strict'
        app.controller('myController', function ($scope, myService) {

            myService.getJSON().then(function(data){
                $scope.myData =data;
            });
            console.log($scope.myData);
        });

Although the http call returns a JSON value successfully, the console log displays 'undefined' for the value of myData. Can anyone help me figure out what mistake I might be making?

Answer №1

Embed the console.log within

 myFunction.getData().then(function(result){
                $scope.data = result;
                console.log($scope.data);
 });

DEMO

Answer №2

To resolve this issue, make the following changes to your controller code:

'use strict'
    app.controller('myController', function ($scope, myService) {

        myService.getJSON().then(function(data){
            $scope.myData =data;
            console.log($scope.myData);
        });

    });

The reason for this problem is that the getJSON method is asynchronous, meaning the request does not wait for a response. Adding a console.log in the ".then" block will address this issue.

Furthermore, when using getJSON, you are utilizing the concept of "promises". For more information on this concept with $http, please refer to the following link:

https://docs.angularjs.org/api/ng/service/$http

Answer №3

Make sure to update the code in the controller section

'use strict';
app.service('myService', function($http) {
    this.fetchData = function() {
     return $http.get('someUrl/dataForm').then(function(response){
            return response.data;
        });
    };
});

controller

  'use strict'
   app.controller('myController', function ($scope, myService) {
        myService.fetchData().then(function(data){
            $scope.myData = data;
           console.log($scope.myData);
        });
    });

Answer №4

  1. $http.get() will return a promise object.

  2. The promise object contains methods like then(), catch(), finally().

  3. When successful, then() is called, and when there is an error, catch() is called.

    Update your service to,

app.service('myService', function($http) {
  this.loadData = function() {
    return $http.get('someUrl/dataForm'); //returns a promise object
  };
});

and the controller to,

app.controller('myController', function($scope, myService) {
  var promise = myService.loadData();
  //then method gets called after resolving
  promise.then(function(data) {
    $scope.myData = data;
    console.log($scope.myData);
  });
});

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

How does the value of the first object key compare to the value of another object key?

I have an array of objects (data 1) and a mapping object. I am trying to create a logic that checks if the 'id' key in the objects of the array and their 'subarr' objects is equal to 1, and if that value matches a key in the mapping obj ...

What is the best way to ensure that the content container's max-width for a split tier is the same as the width of a full-width tier?

My goal is to create a split tier on a webpage with a 60/40 layout. The size of this tier should be calculated based on the maximum width of the container above it. Using JavaScript and jQuery, I managed to derive the max-width value of the full-width-tier ...

A common occurrence is for jQuery/Javascript Ajax POST to generate 6 identical posts when used within a .each loop, happening approximately 20

Context: Building a jQuery mobile phonegap application with multipage-ajaxload and sisyphus enabled form that utilizes an AJAX POST loop to interact with a GUI database. The process involves posting 171 section entries, along with one summary entry to a se ...

Automatically Dismissing a Bootstrap Alert After a Set Number of Seconds

Having some trouble closing a Bootstrap alert automatically on my new site built using the Bootstrap Framework. The issue arises when trying to close the alert after a certain amount of time. On the main page of the site, there is a modal login form. When ...

How can you modify a variable's scope in Angular from a Rootscope function?

Within my rootscope, there is a common function that multiple controllers are using. I am looking to update the Scope variable from the Rootscope Function. http://jsfiddle.net/qkZHG/ In JavaScript angular.module('myApp', []) .run(function($ ...

When the user modifies the input, React fails to update the component state

Currently, I am utilizing React in conjunction with express to server-side render the views for my project. However, I have encountered a minor setback. Within one of my components, users are directed after their initial login. Here, they are prompted to ...

Modify the item in an array using values from a different item in the same array

Within my code, I am juggling two arrays. The first contains multiple objects, while the second stores serialized form data mapped to JSON. Both arrays share identical keys. My goal is to dynamically update the values of an object in the original array ba ...

Delay the execution of Jquery until the openfile dialog box is closed

When I trigger the following code: $('#encoderPreset').trigger('click'); on this input element: <input id="encoderPreset" type="file" name="name" style="display: none;" accept=".EPR" /> A file dialog opens. However, the issue ...

Creating an illustration with HTML5 from an image

Is it possible to draw on an image by placing a canvas on top of it? I am familiar with drawing on a canvas, but I am facing an issue where clicking on the image does not trigger the canvas for drawing. How can I resolve this? This is how my HTML looks: ...

Transmit data from JavaScript to Django via POST request

Attempting to send a POST request with variables to Django. Sending from JavaScript: function submitData(csrftoken, song_id, answer) { fetch('request/', { method: 'POST', headers: { 'X-CSRFToken ...

Limiting the number of promises in AngularJS

My web application allows users to select multiple files using a file input. After the user selects the files, I upload them one by one through my REST API. However, in Internet Explorer, if the user selects more than 10 files at once, some of the requests ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

Can you explain the concept of injection context within Angular version 16 and later?

I have come across the term "Injection context" and am trying to understand what it entails. In Angular, there are several things that are connected to injection context: EnvironmentInjector#runInContext injectionContext runInInjectionContext inject() Fr ...

Pause rendering of Three.js when the video texture needs to be updated

I attempted to apply a video as a texture on a mesh, and tried two different examples: and Both examples worked fine online but didn't display anything when downloaded from GitHub. When I added the code: videoTexture.needsUpdate = false; the floo ...

The compass is currently not displaying the magnetometer values

Hello! I am currently working on a code that displays the values of the magnetometer's (x, y, z) components. Unfortunately, the issue I am facing is that the code keeps returning a "null" value continuously. You can find the link to my expo snack here ...

Is the top bar feature malfunctioning in version 4.3.2 of Foundation?

During my previous project, I utilized the open-source Foundation 4 framework and successfully implemented a top bar navigation. Now, as I embark on a new project with Foundation, I have downloaded the Foundation 4.3.2 version from . Despite referencing th ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

The video is unavailable due to issues with ImageKit

In my project, I am incorporating ImageKit into the workflow. Currently, I have set up a basic process that only includes the video upload feature. On the backend, I have a lone file named index.js. I haven't developed a frontend yet, so I have been e ...

Shutting down the server following the completion of the mocha test, yet the data remains intact

Currently, I am working on testing some data using a REST API. The data is stored as an array within the project. My goal is to have the data "reset" every time a test suite runs, so that I can accurately determine the amount of data in the array. Howeve ...

Navigating Through the DOM with Selenium using XPath Axes

Currently, I am developing Selenium tests for a dynamic web page. Within this section of code, I am extracting data from an Excel sheet and verifying if a specific element exists on the webpage. I have annotated the critical part of the code with comments ...