Using AngularJS: Implementing asynchronous $http.jsonp request through a service

I am currently developing a straightforward application that involves the following steps: 1. The user provides 2 parameters and clicks a button 2. Angular communicates with an external JAVA Servlet that sends back JSON data 3. The application displays the JSON string on the screen

However, I have encountered a problem where nothing happens when I click the button. I suspect that this issue arises because the asynchronous call returns a null variable.

Key pieces of code:

controllers.js

function myAppController($scope,kdbService) {
    $scope.buttonClick = function(){
        var dat = kdbService.get($scope.tName,$scope.nRows);
        $scope.data = dat;

    }
}

services.js

angular.module('myApp.services', []).factory('kdbService',function ($rootScope,$http){
    var server="http://localhost:8080/KdbRouterServlet";
    return {
        get: function(tname,n){
            var dat;
            $http.jsonp(server+"?query=krisFunc[`"+tname+";"+n+"]&callback=JSON_CALLBACK").
                success(function(data, status, headers, config) {
                    console.log("1");
                    console.log(data);
                    dat=data;
                }).
                error(function(data, status, headers, config) {
                    alert("ERROR: Could not get data.");
                });
            console.log("2");
            console.log(dat);
            return dat;
        }
    }
});

index.html

<!-- Boilerplate-->
<h1>Table Viewer</h1>
<div class="menu" >
    <form>
        <label for="tName">Table Name</label>
        <input id="tName" ng-model="tName"><br>
        <label for="nRows">Row Limit</label>
        <input id="nRows" ng-model="nRows"><br>
        <input type="submit" value="Submit" ng-click="buttonClick()">
    </form>
</div>
{{data}}
<!-- Boilerplate-->

Upon executing the code and clicking the button, nothing seems to occur. However, when I check the log, the following output is displayed:

2
undefined
1 
Object {x: Array[2], x1: Array[2]}

Evidently, the success function returns after the get function has already completed, resulting in the $scope.data variable being undefined while the data from the jsonp call is accessible.

Is there a more appropriate approach to resolving this issue? Many tutorials suggest assigning the data to the $scope variable within the success function to bypass this problem. I prefer to keep my service detached if feasible.

Any guidance would be greatly appreciated.

Answer №1

i have a suggestion for achieving something similar:

controller

function myAppController($scope,kdbService) {
    $scope.kdbService = kdbService;
    $scope.buttonClick = function(){
        $scope.kdbService.get($scope.tName,$scope.nRows);

    }
}

service

angular.module('myApp.services', []).factory('kdbService',function ($rootScope,$http){
    var server="http://localhost:8080/KdbRouterServlet";
    return {
        data:{},
        get: function(tname,n){
            var self = this;
            $http.jsonp(server+"?
            query=krisFunc[`"+tname+";"+n+"]&callback=JSON_CALLBACK").
                success(function(data, status, headers, config) {
                    console.log("1");
                    console.log(data);
                    self.data = data;
                }).
                error(function(data, status, headers, config) {
                    alert("ERROR: Could not get data.");
                });
        }
    }
});

html

{{kdbService.data}}

OR

use continuation in the get method :

controller

function myAppController($scope,kdbService) {
    $scope.buttonClick = function(){
        kdbService.get($scope.tName,$scope.nRows,function success(data){
           $scope.data = data;
        });
    }
}

service

    get: function(tname,n,successCallback){
        $http.jsonp(server+"?query=krisFunc[`"+tname+";"+n+"]&callback=JSON_CALLBACK").
            success(function(data, status, headers, config) {
                successCallback(data,status,headers,config);
            }).
            error(function(data, status, headers, config) {
                alert("ERROR: Could not get data.");
            });
    }

OR use the $resource service

http://docs.angularjs.org/api/ngResource.$resource ( you'll need the angular-resource module

code not tested.

I want my service to be detached if possible.

then put the "data object" in a "data service" calling a "data provider service". You'll have to call the "data provider service" somewhere anyway. There is no skipping this problem in my opinion, since that's how javascript work.

also use

angular.controller("name",["$scope,"service",function($s,s){}]);

so you will not need to care how parameters are called , as long as they are defined and injected properly.

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

ImageMapster for perfect alignment

I'm struggling with centering a div that contains an image using imagemapster. When I remove the JS code, the div centers perfectly fine, indicating that the issue lies with the image mapster implementation. It's a simple setup: <div class=" ...

The React application is experiencing difficulty in rendering SVG images exclusively on Windows operating systems

My react app runs smoothly on OSX, but encounters issues on Windows due to SVG files: Module parse failed: Unexpected token (2:0) You may need an appropriate loader to handle this file type. <svg xmlns="http://www.w3.org/2000/svg" viewBox="..."> I ...

Deliver the Stripe API response from the backend to the frontend page

I'm struggling to retrieve the response object from Stripe after creating a subscription using npm. import Stripe from 'stripe'; const key = require("stripe")("XXXXXXXXXXXXXXXXX"); export function subscribe(cus, items) { key.subscription ...

Angular: Delete item from list

Having experience with traditional MVC server-side coding, I am now delving into learning Angular. My goal is to create a user interface that allows users to add teams to the competition they have signed up for. To remove teams from the list, I am utilizin ...

Even though `return false` is called, the line of code is still being executed

I am looking for a way to validate user input details before submitting them to the database. I have multiple tabs in a form and one common save button that triggers a save function when clicked, as shown below; $scope.saveFn = function () { $("#activ ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

What is the process for updating a particular div element?

I am currently developing a webpage that allows users to select an item, and the relevant information will be displayed. On this page, I have incorporated two buttons: btnBuy0 and btnBuy1. The functionality I am aiming for is that when BtnBuy0 is clicked ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...

Ensuring consistency in aligning float elements

I've been struggling to create a concept design for my internship project. I aim to have a page with six clickable elements (images). When one is clicked, the others should disappear and the active one moves to the top. I managed to achieve this using ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

After compilation, what happens to the AngularJS typescript files?

After utilizing AngularJS and TypeScript in Visual Studio 2015, I successfully developed a web application. Is there a way to include the .js files generated during compilation automatically into the project? Will I need to remove the .ts files bef ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

Evolutionary JavaScript Adaptations

I am currently working on an HTML project that involves the use of JavaScript with JQuery. In my project, I will be including a map showcasing different images such as 'Abstract', 'Animals', 'Beach' and more. var images = { & ...

Issue with back button functionality when loading page with history.pushState in JavaScript

My current issue involves loading a page via ajax using history.pushState. The page loads successfully, but the back button does not work as expected. I have included my code below for reference: function processAjaxData(response, urlPath){ document.wr ...

Having difficulty defining variables with the user input in an AJAX request

I have created an HTML input for users to enter a zip code, and I have a JavaScript variable set to capture that input. When I console.log this variable, I can see that it is successfully set as a string. However, when I try to make an AJAX call with the ...

Tips for bringing in pictures from outside directories in react

I am new to React and trying to import an image from a location outside of the project's root folder. I understand that I can store images in the public folder and easily import them, but I specifically want to import them from directories outside of ...

Ensuring Secure API Request Distribution

Currently, I am experimenting with distributed API requests. In PHP, I am developing a website that allows users to make requests on behalf of the server. The objective is to distribute these requests among users to maintain scalability even in high-traffi ...

Utilizing jQuery for interacting with iframes

My script functions perfectly on the page, but when I embed it using an iframe, the jQuery features stop working even though the script is written as usual. Even using $.noConflict(); does not resolve the issue. ...

Is there a way to display an XML listing recursively similar to the functionality of an ASP:MENU in the past?

I have been working on converting a previous asp:menu item to JavaScript. Here is the JavaScript code I have come up with: function GetMainMenu() { var html = ''; var finalHTML = ''; finalHTML += '<d ...