Using AngularJS to make asynchronous calls to hprose.httpclient

I am currently facing an issue with my Hprose server and user authentication. My goal is to create a logonService that will return a UserInfo object after the user has successfully logged in. The problem lies in the asynchronous nature of hprose.HttpClient.login() method, which takes seconds to complete. The code within the controller continues executing immediately after creating the logonService instance, resulting in $scope.user always being null and logonService.logon() never being called. I attempted to use $http.get instead, but I couldn't find a way to obtain a Promise object using Hprose. Despite searching on Google for solutions, I have been unable to find anything useful. Does anyone have any ideas on how to resolve this issue? Your help is greatly appreciated.

var app = angular.module("myApp",[])
  .service("logonService", function() {
     var httpclient = new hprose.HttpClient("http://testurl.com:4800/webapi/", ["login"]);
     httpclient.login("userid", "ppt", function(sid) {
        console.log("sid1="+sid);
     }
     this.logon = function() {
        console.log("here I am");
        return something;
     }
    })
   .controller("myCtrl", ["logonService", function(logonService) {
       var user = logonService.logon();
       $scope.user = user;
   }
)

Answer №1

One issue lies in the fact that the code within myCtrl does not wait for the asynchronous result of logonService.logon(). Additionally, there is uncertainty regarding whether httpclient.login() returns promises. Therefore, it is essential to encapsulate it within a $q promise.

var app = angular.module("myApp",[])

app.service("logonService", function() {
    var loginURL = "http://testurl.com:4800/webapi/";
    var httpclient = new hprose.HttpClient(loginUrl, ["login"]);

    // wrap login function with a new $q promise
    this.logon = function(userid, ppt) {
        return $q(function(resolve,reject){ 
            httpclient.login(userid, ppt, function(sid) {
                console.log("sid1="+sid);
                // determine resolve or reject based on callback results
                if (sid) {
                resolve(sid);
                } else {
                reject('sid wasn\'t defined!');
                }
            })
        }
    }

})

app.controller("myCtrl", ["logonService", 
    function(logonService) {
        logonService.logon(userid, ppt).then(function(user){
            // assign user to scope only after promise is resolved
            // 'user' argument will be whatever was passed to 'resolve' above
            $scope.user = user; 
        })
        .catch(function(e){
            console.log('An Error occurred: ' + e)
            // handle scenarios like logon server being down, etc.
        })
    }
])

Here is a helpful resource for understanding AngularJS' $q. It provides guidance on creating Promises in various situations.

I trust that this information proves beneficial to you.

Answer №2

var application = angular.module("myApp",[])

application.service("logonService", function() {
    var loginEndpoint = "http://testurl.com:4800/webapi/";
    var httpclient = new hprose.HttpClient(loginEndpoint, ["login"]);

    this.logonUser = function(userId, password) {
        // The result of httpclient.login is already a promise object.
        return httpclient.login(userId, password);
    }
})

application.controller("myCtrl", ["logonService", 
    function(logonService) {
        logonService.logonUser(userId, password).then(function(currentUser){
            // Assign currentUser to scope only after the promise resolved
            // 'currentUser' argument will hold whatever was passed to 'resolve' above
            $scope.currentUser = currentUser; 
        })
        .catch(function(error){
            console.log('An Error occurred: ' + error)
            // Logon server may have been down or other issues
        })
    }
])

The outcome of httpclient.login is already a promise object, eliminating the need to utilize $q for wrapping it.

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

Bootstrap is having trouble displaying the collapsed menu due to the abundance of content on the page

While the menu itself opens without any problems, I am facing an issue where the content within the menu is not visible due to other elements on the page obstructing the view. Ideally, I was expecting the collapsed drop-down menu to appear over the existin ...

Implement ajax functionality to update an object within a JSP page

On my JSP page, I have implemented an accordion list (utilizing Bootstrap 3) with text and a Delete button within each node. When the user clicks on the delete button, that specific list item is removed. To construct the accordion list, I bring in an Array ...

Problem arises with chai-http middleware when employing dynamic imports in chai 5.1.1 version

Currently, I am utilizing npm chai version 5.1.1 which has transitioned to supporting only imports and not requires. My use of dynamic imports has been successful so far. However, I have encountered an issue when incorporating the chai-http middleware with ...

Using Angular's ng-style directive to apply various styles based on multiple conditions and attributes

I am attempting to apply multiple styles to an accordion group using the ng-style directive since ng-class is not compatible with accordions. Here is my current implementation: ng-style="{ border: ivrMessageForm.ivr_messagetitle.$error.required && ...

the angular variable scope has not been defined

Currently, I am developing an angular controller that is configured to utilize the "controller as" syntax: angular.module('app', []).controller('ctrl1', ctrl1); ctrl1.$inject = ['$http', '$compile']; function ctrl ...

Generate a smaller set of information by choosing specific columns within a two-dimensional JavaScript array

Apologies for the simplicity of my question and my limited knowledge in javascript. I am completely new to this language and need some guidance. I have an array of data and I want to extract a subset based on selected columns. Here is a snippet of the init ...

The overlay background is being obscured by surrounding elements

Hey there! I'm experimenting with some basic coding and ran into an issue with an overlay. Here's the site link: Sorry for the strange language. :-) If you click on the button with the tiny icon, you'll notice that the overlay form isn&apos ...

Is it possible to request a GET on a server's JSON file using a specific key?

I am currently working on a project involving an auto-suggestion exercise using a JSON file located on a server. I'm not entirely clear on the web development terminology, so one requirement has me a bit confused: The requirement states: "On the keyu ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...

Is there a way to categorize items by their name in JavaScript?

Currently working with Node, I am in the process of developing an ID3 tag parser to extract the title, album, and artist information from MP3 files. My next step involves organizing the retrieved data by grouping them according to the album name. In my p ...

Implementing a function to load HTML pages upon clicking a button with JavaScript

I need help creating a button that loads an HTML page using JavaScript, without redirecting to the page. However, the current code I have is not loading the HTML page as desired. Here is the code snippet in question: <!DOCTYPE html> <html> &l ...

Unable to achieve the expected results following a MongoDB query

Task at hand involves retrieving user details that match the input search (either by name or email) of the logged-in user. Currently, I'm able to fetch unique users associated with the logged-in user but unable to query based on user inputs. Below i ...

Produce an additional page while remaining on the present one

I have a PHP-based invoice system that displays all customer invoices. I am interested in adding a feature that allows users to print an invoice directly from the list page without navigating away. While I am familiar with window.print() and media="print" ...

Guide to managing items in a list using Ionic

I have created a tabbed ionic application in VS2015. I am looking to incorporate a simple list with the ability to add and remove items, similar to this example of an AngularJS app. Here is my HTML code (tab-chats.html): <ion-view view-title="Chats"&g ...

The CLI feature is not compatible with NextJS Drizzle-Kit

I'm currently utilizing the drizzle auth template and attempting to customize it for Role Based Authentication. I've made adjustments in the db.ts file to incorporate roles. import { drizzle } from 'drizzle-orm/postgres-js'; import { pg ...

Exploring the Evolution of jsAjaxForm from jQuery Version 2.1.3 to Version 3.2.1

I'm in the process of upgrading to a higher version of jQuery (3.2.1) and encountering difficulties with updating the ajax file upload functionality using jsAjaxForm from jQuery v2.1.3. Is there a similar function that performs the same role as jaAjax ...

Angular throws an error when trying to parse undefined data outside of an async function

I'm having trouble parsing data retrieved from an http call and passing it to ngOnInit. Can you assist me in finding a solution? My project is built with Angular 4. Here's the async function: async getAsyncData() { this.asyncResult = awai ...

Encountered an unknown getter error in Vuex while using Vue/Nuxt/Vuex with server-side rendering enabled

I am encountering an error when I try to loop through the 'allPosts' data using a v-for directive on my div element. Could it be possible that I have missed something related to the namespaced module transformation as mentioned in the Nuxt docum ...

AJAX Communication Issue: Data not transferring from client-side to backend in C# MVC 5 via HTTP

I've encountered a problem with sending data from a JavaScript frontend to my C# MVC 5 backend. Despite debugging the code in Visual Studio, the data I'm trying to pass always ends up as null. Below is my front end code: var file = $("#my-file" ...

"Utilize jQuery AJAX Promises to Trigger Custom Exceptions that can be Handled by the Outer fail() Function

Imagine having a function that yields a promise. The promise returned is scrutinized by other functions to determine how to manage the .fail() condition. function refreshTimeline() { var promise = ajaxMethod1() .then (function (data) ...