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

Switching between fixed and unfixed divs causes two absolute divs to alternate

I am currently working on a code to keep a fixed div ("two") in place between two absolute positioned divs ("one" and "footer") while scrolling. However, there is an issue that arises when the browser window is resized. The distance between the footer and ...

Looking for guidance on utilizing pushState and handling onpopstate events?

By using ajax, I am able to load specific page content without refreshing the entire page. In order to make the back button functionality work, I utilize pushState and onpopstate as shown below: function get_page(args){ .... $.ajax({ url ...

What is the best way to reload DataTables using an ajax/error callback?

In my code, I am customizing the default settings of DataTables like this: $.extend(true, $.fn.dataTable.defaults, { lengthChange: false, deferRender: true, displayLength: 25, stateSave: false, serverSide: true, processing: true, ...

How to properly size a child div inside a parent container

I'm having trouble with sizing a child div inside a parent div. The problem is that the child div's size changes according to the number of elements it contains, but I want all the child divs to be the same size regardless. This issue arises with ...

What distinguishes setting a $watch on a string variable from setting a $watch on an object's key in AngularJS?

When using angularJs, I am curious about the distinction between setting $watch on a string variable versus setting $watch on an Object's key. Let me explain with a detailed scenario: $scope.activeMenu = {'id' : '...', 'name ...

Sending an HTTP GET request to an API can result in different outcomes depending on whether it is sent to localhost or to a remote server. In some cases, the

My setup involves Angular for the front end and Slim for the back end. Interestingly, when I send a request locally, everything functions smoothly, and I receive the JSON response as expected. http://localhost/domain/api/jobs However, the situation chan ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

Disabling a DropDownList in ASP MVC when a checkbox is marked: A step-by-step guide

Currently, I am in the process of developing an application using ASP .Net MVC 3 with C# and SQL Server 2005. Additionally, I am incorporating Entity Framework along with the Code First Method for this project Within a specific view, there are 2 checkbox ...

Find the item in the pop-up window

When removing a user from my list, a JavaScript popup pops up prompting to confirm the action with two buttons "OK" / "Annuler" : Is there a way to use Selenium to find and interact with these buttons? ...

Passing Variables from Node JS to Pug Template's HTML and JavaScript Sections

Here is a route that sends various variables to a Pug template: items.js route router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeExp ...

Including an additional row in a pre-existing table

My goal is to dynamically add a new row when a button is clicked, right after the row containing the button. To achieve this, I'm using jQuery (version 1.10.2) to handle the creation of new rows. The issue I'm facing is related to the behavior o ...

Displaying object values in text fields based on dropdown item selection

Displaying the dropdown: <h:outputLabel value="#{build.approvedRecons}" for="reconSearchFunctionalAreaID"></h:outputLabel> <p:selectOneMenu style="width:200px;" id="reconSearchFunctionalAreaID" > <f:selectItem itemValue="- ...

tips for choosing tags that are nested within specific parent tags

I'm looking to locate and count all the <"a"> tags within every <"code"> tag on a given webpage using JavaScript. How can I accomplish this? I attempted methods like document.getElementsByTagName("code").getElementsByTagName("a"); and document. ...

Using PHP to send post requests with Ajax for DataTables functionality

I'm currently working on populating a datatable using datatables.net. There's a specific field that triggers an AJAX post request after it's changed. Here is the JavaScript code: jQuery(document).ready(function() { if(window.location.h ...

The module specifier "tslib" could not be resolved due to a TypeError. It is necessary for relative references to begin with either "/", "./", or "../"

Hey there, I recently started learning npm. I'm trying to install "@fullcalendar" and use it, but I keep getting this error message: "Uncaught TypeError: Failed to resolve module specifier "tslib". Relative references must start with either "/", "./", ...

What is the best way to incorporate npm packages into my projects?

Lately, I've been heavily relying on nodejs, but I keep running into the same issue. With so many projects available and a plethora of npm packages to choose from, it's frustrating that every time I try npm install --save some-package, I struggle ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...

Issues with jQuery autocomplete functionality on certain elements are not uncommon

I've been experimenting with creating a user script for Opera using Greasemonkey to implement autocomplete functionality on input elements within web pages. However, I've encountered some issues with the script not working as expected. Initially ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

Encountered an error: Unable to access property '0' of an undefined variable

Below is the script I am using: <script> var count; var obj; function search() { xhr = new XMLHttpRequest(); xhr.open("GET", "test.json", true); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 & ...