Revealing confidential information in Angular's http get request's internal scope

I am a beginner in Angular and I am currently developing an application that retrieves data from an accounting software and uses Google Charts to visualize various elements.

Unfortunately, the API of the accounting software does not provide the data in the required format, so I have to process it before passing it on to the Google Charts API.

The issue I am facing is that I cannot access the data returned inside the HTTP GET request function due to scope limitations. I have attempted several solutions without success. It seems like there should be a straightforward solution to this problem, but I can't seem to figure it out.

If anyone could assist me with a method to expose HTTP request data for use outside of the function itself, I would greatly appreciate it.

    myApp.controller("dataFetch", ['$http', '$scope',function($http, $scope){

    var self = this;
    self.project = {};
    self.TSproject;
    self.TShours;

    //PASSING AUTHORIZATION
    var config = { headers: { 'Authorization': 'Bearer 1lFASlwgM3QwSyZfJVJPO6776X5wlZtogdg8RN-Lt',} };

    //GET DATA
    $http.get('https://api.freeagent.com/v2/projects/941562', config).then(function(response) {

        //SAVING PROJECT DATA
        self.project = {
            name: response.data.project.name,
            url: response.data.project.url
        };
        return self.project.url;

    }, function(errResponse) {
        console.error("Get project request failed");
    }).then(function(pUrl) {
        return
        $http.get('https://api.freeagent.com/v2/timeslips?' + 'from_date=2015-09-21&to_date=2015-09-28' + 'user=' + pUrl, config).then(function(response) {
            self.TSproject = response.data.timeslips[0].project;
            self.TShours = response.data.timeslips[0].hours;
        });

    });
    //GOOGLE CHARTS  
    $scope.data1 = {};
    $scope.data1.dataTable = new google.visualization.DataTable();
    $scope.data1.dataTable.addColumn("string","User")
    $scope.data1.dataTable.addColumn("number","Qty")

    //INSERTING DATA FROM SERVER HERE
    $scope.data1.dataTable.addRow([self.TSproject, self.TShours]);
    $scope.data1.title="Daniels Timeslips";

}]);

Thank you!

Answer №1

Your code is facing an issue due to the premature initialization of your charts before the completion of the GET call.

Despite $http.get() appearing first in the code, it operates asynchronously. Therefore, the JS interpreter will not wait for the call to finish. It will proceed with executing the AJAX call using $http.get() and then move on to other statements, like initializing Google Charts in this scenario.

Once the response is obtained, promises should be used to trigger events after the AJAX call is done. This is where you should ideally set up your charts, as they rely on the data from the AJAX call.

To resolve this issue, simply relocate the charts initialization to the callback function of your second GET request, as shown below:

$http.get('https://api.freeagent.com/v2/projects/941562', config).then(function(response) {
  // Your code here
}, function(errResponse) {
    console.error("Get project request failed");
}).then(function(pUrl){

    $http.get('https://api.freeagent.com/v2/timeslips?' + 'from_date=2015-09-21&to_date=2015-09-28' + 'user=' + pUrl, config).then(function(response){
        self.TSproject = response.data.timeslips[0].project;
        self.TShours = response.data.timeslips[0].hours;

      // GOOGLE CHARTS  
      $scope.data1 = {};
      $scope.data1.dataTable = new google.visualization.DataTable();
      $scope.data1.dataTable.addColumn("string","User")
      $scope.data1.dataTable.addColumn("number","Qty")

      // INSERTING DATA FROM SERVER HERE
      $scope.data1.dataTable.addRow([self.TSproject, self.TShours]);
      $scope.data1.title="Daniels Timeslips";
    });

});

Answer №2

Consider embedding the google chart object within the final http promise for better organization.

    //GET DATA
    $http.get('https://api.freeagent.com/v2/projects/941562', config).then(function(response) {

        //SAVING PROJECT DATA
        self.project = {
            name: response.data.project.name,
            url: response.data.project.url
        };
        return self.project.url;

    }, function(errResponse) {
        console.error("Get project request failed");
    }).then(function(pUrl) {
        return
        $http.get('https://api.freeagent.com/v2/timeslips?' + 'from_date=2015-09-21&to_date=2015-09-28' + 'user=' + pUrl, config).then(function(response) {
            self.TSproject = response.data.timeslips[0].project;
            self.TShours = response.data.timeslips[0].hours;

            //GOOGLE CHARTS  
            $scope.data1 = {};
            $scope.data1.dataTable = new google.visualization.DataTable();
            $scope.data1.dataTable.addColumn("string","User")
            $scope.data1.dataTable.addColumn("number","Qty")

            //INSERTING DATA FROM SERVER HERE
            $scope.data1.dataTable.addRow([self.TSproject, self.TShours]);
            $scope.data1.title="Daniels Timeslips";
        });

    });

You can now access {{ data1 }} in your template to view all the information.

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

Ways to Enhance the Display of Comments in a Chat Box Using JavaScript and PHP

I have created a chat box, but I am facing an issue when trying to delete an unwanted comment. The problem lies in the delete function associated with an onclick event for each inserted comment. The comments are stored in a database. var refreshMsg = setI ...

Guide to inserting nested arrays into a MongoDB database using Node.js

I'm attempting to send Product data to a mongo database using mongoose. Product Model var mongoose = require('mongoose'); var Schema = mongoose.Schema; var productsSchema = new Schema({ // productId: {type: _id, required: true, au ...

Angular.js testing for inject() function runs before the execution of a run phase code block

I am facing a situation where I need to load HTML5 Audio specifically for mobile devices, which requires user interaction like ontouchstart. To achieve this, I have implemented the necessary logic in an Angular run phase to ensure it is executed at the ear ...

Unable to change the value of Apexcharts components

Utilizing the Vue.js framework along with the Apexchart library, I have been able to create scatterplots for my data. By making use of Axios, I can successfully transmit my data and monitor it using console.log(). With the help of Apexcharts property updat ...

Swiper: What methods can be used to classify the nature of an event?

Currently, I am utilizing Swiper for React in my project. I find myself in need of implementing a different effect when the user swipes versus using buttons to switch between active slides. Upon examining the swipe object for pertinent details regarding ...

How can we determine the nL and nH values using an ESC/POS command?

Looking to adjust the printer's head position using ESC / pos commands: ESC $ command sets the absolute horizontal position ESC $ nL nH Trying to figure out how to calculate the values for nL and nH? ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

"Learn the process of sending a post request using a combination of JQuery, Ajax

I am attempting to send a post request with the following code - var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { $scope.data = {}; $scope.reqCalling = function () { ...

Error: ...[i] has not been defined

What seems to be the issue with this part of the script: function refreshLabels() { // loop through all document elements var allnodes = document.body.getElementsByTagName("*"); for (var i=0, max=allnodes.leng ...

Exploring the Mystery of why Three.js Fails to Apply Textures to Objects

I'm attempting to add a texture to an object with the following code: <html> <head> <title>My first Three.js app</title> <style> body { margin: 0; } canvas { width: 100%; h ...

What is the best way to access a URL value in an MVC framework?

I'm facing a small issue and need some assistance. I am using AngularJS to pass information to an MVC controller, specifically passing a user ID for the admin to change a user to an administrator. Below is the code snippet for the view: <tr ng-re ...

Unable to eliminate top margin in Bootstrap 3 affix feature

Struggling to locate the source of the margin-top when utilizing the affix plugin on my Navbar. You can view [my website here] for better understanding. Should I be implementing Javascript to solve this issue? My current skills in that area are not very ...

Is it possible to have an Iframe that contains content but no src attribute?

During the process of troubleshooting jQuery code on their website (using the Chrome Developer Toolbar), I came across an interesting observation. I found that their examples were embedded within an Iframe: Here, for instance, there is a sample displayed ...

Express is having trouble providing data to React

Currently, I am delving into mastering the realms of React and Express. My ongoing project involves crafting a learning application that fetches data from MySQL and renders it visually for analysis. To kickstart this endeavor, I set up a basic express ser ...

What is the best way to connect an external JSON file to an Angular controller?

As I embark on my first Angular JS project, I find myself in need of exporting a JSON array from my controller to an external JSON file. Here is the snippet from my controller containing the JSON data: Fantacalcio.controller('fantacalcioController&ap ...

Radio button value failing to display accurately

I seem to be encountering a problem with the radio buttons. I am pulling all the necessary information such as labels, components, etc. from JSON and displaying it on the view. For example, when I retrieve two values for the component of a radio button fr ...

Generate an array containing all N-digit numbers with a sum of digits equal to S

I encountered a problem with my code translation process. Despite finding solutions in other languages, when I converted them to javascript, the expected array was not created. const find_digits = (n, sum, out, index) => { if (index > n || sum & ...

Creating an Ajax Post request for API invocation

I'm currently setting up an Ajax Post request to interact with an API. Here is a mock curl command for reference: curl -X POST \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --h ...

Open a webpage and execute JavaScript with just one click of a bookmark

I found a convenient bookmark that opens my Google Calendar page at http://www.google.com/calendar/renderOnline. Additionally, I have another bookmarklet that applies specific JavaScript to the page: javascript:document.getElementById('gadgetcell&apo ...

Converting a JavaScript array into JSON using PHP

After analyzing the text, I was trying to figure out how to convert it into json format using php's json_decode function. Unfortunately, when I used json_decode on this text, it returned a syntax error. $arr = json_decode($str, true); {1: {name: &ap ...