A Guide on Accessing Promise Results in AngularJS

In my code, I am using a controller to retrieve information from SharePoint. While debugging, I noticed that the value of

data.d.UserProfileProperties.results[115].Value
is what I need to display in the view. However, I am struggling to extract that value from the result promise. How can I achieve this?

(function() {
    'use strict'
    var createPurchasingCardController = function($scope, $rootScope, $filter, $window, $location, $timeout, requestService) {        

        $scope.actionTitle = "";
        $scope.counter = [];                      

        var getCurrentUserData = function () {

            var dfd = new $.Deferred();
            var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
            $.ajax({
                url: queryUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: onSuccess,
                error: onError,
                cache: false
            });

            function onSuccess(data) {            
                dfd.resolve(data);                    
            }

            function onError(data, errorCode, errorMessage) {
                dfd.reject(errorMessage);
            }

            return dfd.promise();               
        }            

        var _init = function () {                
            $scope.counter = getCurrentUserData();
            console.log($scope.counter);
        }

        _init();

    }

    angular.module('myApp').controller('createPurchasingCardController', ['$scope', '$rootScope', '$filter', '$window', '$location', '$timeout', 'requestService', createPurchasingCardController]);
}());

I have attempted to store it in the counter variable, but the value is not displaying. If you have any suggestions or solutions, I would greatly appreciate your assistance.

Answer №1

If you want to move away from using jQuery's .ajax method, consider utilizing AngularJS's $http service:

function getCurrentUserData() {
    var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
    var promise = $http({
        url: queryUrl,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        cache: false
    }).then(function(response) {
        return response.data;
    }).catch(function(response) {
        console.log("ERROR", response);
        throw response;
    });

    return promise;               
} 

After getting the data from the promise:

function _init() {                
    var promise = getCurrentUserData();

    promise.then(function(data) {
        $scope.counter = data;
        console.log($scope.counter);
    });     
}

_init();           

The promises returned by AngularJS's $http service are seamlessly integrated with the AngularJS framework, allowing for benefits such as data-binding and exception handling within the AngularJS context.

To learn more, check out:

Answer №2

Set the response object to the $scope object.

function handleSuccess(result) {            
    $scope.apiData = result;
    dfd.resolve(result);                    
}

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

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

Obtain the origin of the image using dots in Javascript

Sharing my experience with setting a background image using Javascript. Initially, I tried using two dots like this: .style.backgroundImage = "url('../images/image00.jpg')" However, it did not work as expected. So, I removed one dot: .style.ba ...

Desktop Safari displays Font-awesome icons with trimmed corners using a border-radius of 50%

While working on incorporating font awesome share icons into my project, I encountered an issue with getting a circle around them. After exploring various approaches, I opted for a CSS solution. Using React FontAwesome posed some challenges that led me to ...

Steps for clearing input field with type=date in Protractor:

I am currently working with protractor version 4.0.4 and I'm encountering an issue where I cannot clear a date input field. It seems like Chrome is introducing some extra controls that are causing interference. You can find further details about Chro ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

Unable to access account due to login function malfunctioning

I've created a login button with this function code, but I keep getting the error message "Login unsuccessful, Please try again..." Thank you in advance. I wasn't entirely sure what you needed, so I included most of the code because I've b ...

Exception in posting strings or JSON with react.js

Whenever a user clicks on the Signup button, the process I follow to create an account is as follows: Firstly, a new User entry is created in the database. createUser = () =>{ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http:// ...

Mastering asynchronous function handling in Node.js

I'm currently experiencing an issue with printing two statements using two functions var mongoose = require( 'mongoose' ); var_show_test = mongoose.model( 'test' ); exports.showTest = function(req,res) { var jsonString = []; ...

The process of initializing the Angular "Hello World" app

Beginning with a simple "hello world" Angular app was going smoothly until I attempted to add the controller. Unfortunately, at that point, the expression stopped working on the page. <!doctype html> <html ng-app='app'> <head> ...

identifying HTTP requests originating from an embedded iframe

I have a unique scenario where there is an iframe on my page that calls a URL from a different domain. Occasionally, this URL will tunnel to a different URL than the one I specified. Unfortunately, due to cross-domain restrictions, I am unable to view the ...

Troubleshooting Issues with Implementing JavaScript for HTML5 Canvas

I've encountered an issue with my code. After fixing a previous bug, I now have a new one where the rectangle is not being drawn on the canvas. Surprisingly, the console isn't showing any errors. Here's the snippet of code: 13. var can ...

Strategies for optimizing progressive enhancement

Designing a website that is accessible to everyone is truly an art form, and Progressive Enhancement is something I hold dear... I am curious to hear about the best techniques you have used to ensure websites work for all users, regardless of their browse ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

The GraphQL Resolver function that returns an object

When querying with GraphQL, I receive results in the following format: { "data": { "events": [ { "_id": "65f0653eb454c315ad62b416", "name": "Event name", " ...

Creating a dynamic dropdown menu in HTML to showcase a variety of images

I am trying to create a drop down menu where each selection displays multiple elements. For example, if sensor 1 is chosen, I want to show a picture of its location and its address. I am having trouble figuring out how to add these functions to the drop ...

What is the maximum number of requests that Node-Express can send simultaneously?

Currently, I am facing a challenge with my script that involves fetching 25,000 records from AWS Athena, a PrestoDB Relational SQL Database. For each of these records, I need to make a request to Athena and then another request to my Redis Cluster once the ...

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

What is the process to ensure a promise resolves as an object in the view?

I am attempting to create a wrapper for a third-party library that will return an object that resolves into a format suitable for display in the view, similar to how $resource() functions. I understand that I can manually use .then() on the promise and set ...

Tips for creating a threaded commenting feature in Django

Currently, I am working on developing a commenting system using Django. Here's what I have accomplished so far: I have implemented AJAX initial comments where the parent comment is appended without requiring a page refresh and saved to the databas ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...