Extracting user information from the Promise object in a JHipster application: A step-by-step guide

I am currently working on creating an 'Order' object in the frontend and attempting to push it into the database using REST services. The POJO of the 'Order' looks like this:

@NotNull
@Field("total")
private BigDecimal total;

@Field("status")
private String status;

@Embedded
public User user;

At the moment, I have a 'Principal' service that provides information about the currently logged-in user. When I use 'console.log(Principal.identity())', it returns the following result with the 'User' data inside the '$$state' Object.
https://i.sstatic.net/VS0sY.png I am struggling to figure out how to extract the 'user' data from the promise object and add it to the 'Order' object. I have come up with a method to retrieve user data by delving into the Promise object as shown below, but I'm unsure about its effectiveness. https://i.sstatic.net/92H8p.png

Is there a more optimal way to extract data from the Promise in this particular scenario?

EDIT: This application is based on JHipster. Below is the code for the "Principal" service:


            'identity: function (force) {
            var deferred = $q.defer();

            if (force === true) {
                _identity = undefined;
            }

            // check and see if we have retrieved the identity data from the server.
            // if we have, reuse it by immediately resolving
            if (angular.isDefined(_identity)) {
                deferred.resolve(_identity);

                return deferred.promise;
            }

            // retrieve the identity data from the server, update the identity object, and then resolve.
            Account.get().$promise
                .then(function (account) {
                    _identity = account.data;
                    _authenticated = true;
                    deferred.resolve(_identity);
                    Tracker.connect();
                })
                .catch(function() {
                    _identity = null;
                    _authenticated = false;
                    deferred.resolve(_identity);
                });
            return deferred.promise;
        }'

Here is the method generated by JHipster to receive resources from the server using ngResource.

'angular.module('hotSpiceApp')
.factory('Order', function ($resource, DateUtils) {
    return $resource('api/orders/:id', {}, {
        'query': { method: 'GET', isArray: true},
        'get': {
            method: 'GET',
            transformResponse: function (data) {
                data = angular.fromJson(data);
                return data;
            }
        },
        'update': { method:'PUT' }
    });
});'

Answer №1

When utilizing the Principal.identity() function, it is important to note that it returns a Promise. For more information on promises, you can refer to this link.

To properly handle the returned user data, you can structure your code as follows:

Principal.identity().then(function (user) {
  var data = {
    // other fields
    user: user
  };
  // Perform operations with 'data' within this inner function
});

It is not recommended to access the user data using

Principal.identity().$$state.value
. This approach relies on Angular's internal promise implementation and may not work consistently in every scenario. Asynchronous nature of promises means that the data retrieval process happens after making a request to the server. Therefore, attempting to access
Principal.identity().$$state.value
before the promise is resolved will result in a value of undefined.

Furthermore, it is crucial to avoid passing current user data directly from client-side JavaScript to the server. Instead, retrieve the user information on the server side (from session variables or similar mechanisms) upon receiving the request. By handling user-specific data on the server side, you minimize security risks associated with allowing potentially harmful input from the client-side code.

Answer №2

Could you please elaborate on how you go about fetching the principal service? If it returns a promise, make sure to assign the desired data to a local variable within the "then" method.

To inspect the contents of the "Principal" service, you can utilize the following code in the Chrome console:

angular.element(document.querySelector('html')).injector().get(Principal);

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

Creating a standalone module using webpack that can be accessed through a script element

When setting the library target to 'umd' in the package.json file, the expectation was that the outputs would be usable via a <script> tag and if no module system was available it would be attached to the window. However, this does not seem ...

Using $scope.$apply() to generate several instances of a fresh scope

Currently, I am working on setting up a provider and factory within Angular. Most of the heavy lifting, such as generating templates, creating instances, and handling animations, takes place in the factory. The provider, on the other hand, is responsible f ...

What are the practical uses for lodash's "nth" method?

When working with complex nested arrays, the lodash function _.nth(array, n) provides a more structured and easier to read approach in accessing specific elements. Although using array[n] may seem more concise in simple cases, the lodash function can be mo ...

Troubleshooting issues with ASP.NET bundling and minification when using Angular.js

After reviewing many questions on the same topic, none of them were able to solve my specific case. Our current challenge involves bundling and minifying AngularJs files within .Net code. The following code snippet shows how we are bundling our files insi ...

Execute a JavaScript function once the ASP.NET page finishes loading

Is there a way to execute a javascript function from ASP.NET code behind once the page has fully loaded? I've tried the following code, but it seems that the hidden field is not populated with the value before the javascript function is called, resul ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

What is the best method for initializing Bootstrap data attributes API?

I've been puzzled by this issue for a while now. When trying to use the JavaScript components, I can't seem to grasp how to utilize them using the Data Attributes API, also known as the first-class API. For example, take the modal component ment ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

What is the best way to dynamically load utility methods in a Next.js application?

Do you believe it is beneficial to organize logic into utility files and dynamically load them to enhance the speed of a website? For example, I have a method called getInvoiceDetails in a file named getInvoiceDetails.tsx: export default const getInvoiceD ...

Best method to determine if three points in time are less than thirty minutes apart

In the form, there are 3 date/time input boxes with a requirement that the user cannot select times within half an hour of each other. I successfully converted all values to epoch format using a Javascript version of strtotime. However, I am unsure how to ...

I am interested in executing a series of consecutive queries to MySQL through Node.js, however, only the final query seems to be executed

connection.query(listprofiles,function(error,profilesReturned){ console.log(profilesReturned.length) for (var i=0;i<profilesReturned.length;i++){ console.log(profilesReturned[i].column) var query2='SELECT IF(COUNT(*) & ...

A guide to quickly obtaining the width and height of an element as it resizes in Vue.js

Is there a way to immediately get the width and height of an element when it is resizing in Vue.js? I have created a Codepen illustration and would appreciate any help in making it function correctly, thank you! Codepen let app = new Vue({ el: &apos ...

Collision Detection within a THREE.Group in Three.js

Currently, I am tackling the challenge of detecting 3D AABB collisions between a box and a sphere. An interesting observation: when a box is directly added to the scene, collisions are detected successfully. However, when the box is added to a group (THRE ...

Resolving parent routes in Angular 2

I am encountering an issue with my code. The 'new' route is a child route for the 'users' route. The 'users' route has a resolver, and everything works fine up to this point. However, after successfully creating a new user, ...

What is the best way to dynamically generate a component and provide props to it programmatically?

I am interested in creating a function that can return a component with specific props assigned to it. Something like a reusable component for Text/View/Pressable, where styles can be extracted and passed as props. Personally, I find it more efficient to s ...

Is there a way to incorporate electron methods within Svelte files, specifically in Svelte 3, or is there an alternative approach to achieve this integration?

Currently, I am deep into a project that involves Svelte 3 and Electron 12.0.5 working together harmoniously. For managing hash routing, I have integrated the svelte-spa-router package into my setup. Here is a glimpse of how my project structure appears: n ...

Mastering state transitions in Angular JS

Currently, I am developing code to display a simple list of users. Upon clicking on a user from the list, I aim to navigate to a view containing detailed information about that particular user. At this stage, I have successfully implemented the functionali ...

Take away and bring back selections from dropdown menus

My HTML code consists of a select element with options and buttons: <select id="sel"> <option value="1">aaa</option> <option value="2">bbb</option> <option value="3">ccc</option> <option value=" ...

Leveraging ES6 in conjunction with gulp

When working with gulp, I encountered an issue with arrow functions in my Angular JS project build task. Gulp doesn't recognize the arrow functions in my scripts, resulting in errors like: Error: Parsing error: Unexpected token > What cou ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...