Guide on transferring values from a callback function in a service to controllers

How do I retrieve values returned from a service using a controller? In my code, the function showInfo() in service.js returns JSON objects. However, I am unable to access these objects outside of this function. When I attempt to use console.log in controller.js

console.log(chartService.showInfo.new_data)

I receive an

error stating Cannot read property 'new_data' of undefined.

The same issue occurs if I try

console.log(chartService.showInfo)

It returns undefined.

How can I access the new_data JSON object inside the showInfo function from the controller?

Service.js

angular.module('myApp')
   .service('chartService', function (){
  return {
     getUrl: function init(path) {
        Tabletop.init( { key: path,
                         callback: showInfo,
                         simpleSheet: true } )
     }
  }

     function showInfo(data, tabletop){

          var new_data = JSON.stringify(data.map(function(el) {
            return {
                "name": el[Object.keys(el)[0]],
                "y": +el[Object.keys(el)[1]]
            };
     }));
   }
})

Controller.js

angular.module('myApp')    
      .controller('piechartCtrl', [ '$scope', 'chartService',  function (chartService, $scope) {
        console.log(chartService.showInfo.new_data)
    
    }]);

Answer №1

Assistance

angular.module('myApp').service('chartService', function (){
    return {
        initialize: initialize,
        displayInformation: displayInformation
    };

    function initialize(path) {
        return Tabletop.init({
            key: path,
            callback: displayInformation,
            simpleSheet: true 
        });
    }

    function displayInformation(data, tabletop){
        return JSON.stringify(data.map(function(item) {
            return {
                "title": item[Object.keys(item)[0]],
                "value": +item[Object.keys(item)[1]]
            };
        }));
    }
});

Management

angular.module('myApp').controller('piechartCtrl', [ '$scope', 'chartService',  function (chartService, $scope) {
    var tabletop = chartService.initialize(),
        chartDetails = chartService.displayInformation(someData, tabletop);

    console.log(chartDetails);        
}]);

I am not certain about the parameters in displayInformation, but this should give you a good starting point.

Answer №2

One effective way to handle asynchronous operations in Angular is by using Promises. In Angular, you can utilize the q framework through the $q service $q documentation

Service Implementation

angular.module('myApp')
  .service('chartService', function($q) {
    var deferredSpreadsheet = $q.defer();
    return {
      getSpreadsheet: function fetch(path) {

        Tabletop.init({
          key: path,
          callback: showInfo,
          simpleSheet: true
        });
        return deferredSpreadsheet.promise;

      },

    }

    function showInfo(data, tabletop) {

      data = JSON.stringify(data.map(function(el) {
        return {
          "name": el[Object.keys(el)[0]],
          "y": el[Object.keys(el)[1]]
        };
      }));
      deferredSpreadsheet.resolve(data);

    }
  })

Controller Logic

angular.module('myApp')
.controller('piechartCtrl', ['$scope', 'chartService', function($scope, chartService) {

    var path = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html";
    var pro = chartService.getSpreadsheet(path).then(function(data) {
      console.log(data)

    })


  }]);

For a live demonstration, check out this example on Plunker

Answer №3

Not a recommended method: Utilize Broadcast and Emit to achieve the desired functionality

within the Service:

$rootScope.$broadcast('myEvent', JSONDATA);

within the Controller:

$scope.$on("myEvent", function(event, jsonData){
console.log(jsonData);
});

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

Set the background to be transparent while keeping the text opaque

Is there a way to make only my div transparent using the opacity property while keeping the font normal? I cannot assign a separate class or id to the content as it is dynamically generated. Also, using background: rgba(); is not an option for me. {opacit ...

"Troubleshooting an Object Error When Making an Ajax Call in a Spring

Screenshot showing an ERROR I am attempting to input a value using an AJAX call through a Spring MVC controller. However, it is throwing an Object Error when the button is clicked. Can someone please assist me with this issue? CODE: Ajax Code: <scri ...

Basic website layout

As someone who is new to web programming, I kindly ask for your patience :) I have a goal to design a page similar to the one linked below https://i.sstatic.net/HbJF3.png There are two key functionalities I am aiming for: 1) Clicking the button on the r ...

What exactly does the jquery ajax success callback cover?

Is the value of testvar in function AjaxRequest going to increase on success? function AjaxRequest(){ var testvar = 0; for(i=0;i<d.length;i++){ $.ajax({ success: function(a){ testvar++; } ...

Twice Asynchronous AJAX Action

Currently, I am working on a javascript script to dynamically load pages on my website without the need to refresh the entire page. The script involves fading out the content div, loading new content, switching the content, and then fading it back in. The ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Issue with style display:none not functioning in IE8, IE9, and IE10 when in Compatibility View mode

I am facing an issue with two DIVs on my webpage. One of them is set to have display:none based on certain conditions. Surprisingly, it works perfectly fine on IE10, Firefox, and Chrome. However, the problem arises on IE8, IE9, and IE10 Compatibility Vie ...

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...

What steps can I take to resolve the issue of item display in the dropdown menu?

My objective is to have a dropdown list with "title 1234" appearing first. When this option is selected, its value should be 1234. How can I achieve this? Here is the desired outcome: https://i.sstatic.net/CqWgn.png Currently, the list looks l ...

The $scope object in AngularJS has not been properly defined and

I am facing an issue with retrieving the value of email in my controller. It always returns 'undefined'. Here is my form: <form role="form" novalidate> <div class="form-group"> <input type="email" ng-model="user.emai ...

Retrieving a boolean value (from a JSON file) to display as a checkbox using a script

Currently, I am utilizing a script to fetch data from a Google Sheet $.getJSON("https://spreadsheets.google.com/feeds/list/1nPL4wFITrwgz2_alxLnO9VBhJQ7QHuif9nFXurgdSUk/1/public/values?alt=json", function(data) { var sheetData = data.feed.entry; va ...

Iterating through an array and displaying information according to the quantity in node.js

Hey everyone, I have a simple task at hand where I am working with the following array: {items:[{upc:a,quantity:2},{upc:b,quantity:3}]} My goal is to transform it into the format shown below: {products:[{barcode:a},{barcode:a},{barcode:b},{barcode:b},{bar ...

Unraveling the complexities of double-encoded UTF-8 in PHP

Trying to transmit data from an HTML page via Ajax to a PHP page. This is the jQuery code I'm using: $.ajax({ url: "test.php", type: "POST", data: { name: "João" } }).done(function (data) { alert(data); }) When sending ...

What is the best way to add pairs of divs to a single div?

Can you help me with this task? <div id="list"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div& ...

Locating the right selector for adding a div to its parent element in jQuery

I have come across an interesting HTML structure: <div class="dropdownedit"> <div class="dropbtn">textxyz</div> <div class="dropdown-content" style="display: none;"> <div href="#" class="ocond" id="text1">text1</div> &l ...

"Vue.js and Node.js have been successfully installed, with their respective versions displayed. However, the applications are

kirti@kirti-Vostro-14-3468:~/flipbook-vue$ node --version v17.6.0 kirti@kirti-Vostro-14-3468:~/flipbook-vue$ vue --version @vue/cli 5.0.1 kirti@kirti-Vostro-14-3468:~/flipbook-vue$ npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

New issue with Express js 4x: receiving an empty object from :req.params

Having trouble fetching URL parameters in express js as the object is coming back empty. var password= require('./routes/password'); app.use('/reset/:token',password); password.js router.get('/', function(req, res, next) { ...

Utilizing Images with 'General Drawing' in Highcharts

I'm currently attempting to create a task diagram using Highcharts. I had the idea of incorporating images using the <img> tag ren.label('<img src="/images/test.jepg', 10, 82) .attr({ ...