小编典典

如何使用AngularJS获得承诺结果

ajax

以下是用于从共享点检索信息的控制器。我可以看到调试显示条目data.d.UserProfileProperties.results[115].Value具有需要在视图中呈现的属性值。我如何从结果承诺中获得那个价值?

(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]);
}());

我试图将其放入柜台,但没有显示。任何帮助,将不胜感激。


阅读 251

收藏
2020-07-26

共1个答案

小编典典

不要使用jQuery .ajax,而要使用$ http服务:

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;               
}

然后从返回的promise中提取数据:

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

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

_init();

$
http服务返回的promise已与AngularJS框架集成。只有在AngularJS执行上下文中应用的操作才能从AngularJS数据绑定,异常处理,属性监视等中受益。

有关更多信息,请参见

2020-07-26