使用 REST API 和 angular JS 查询多个 SharePoint 列表

Query multiple SharePoint lists Using REST API and angular JS

我有一个使用 REST API 和 Angularjs 从多个 SharePoint 2013 列表中获取数据的场景。我能够从 SharePoint 列表之一成功获取数据,但我的要求是在页面加载时从多个列表中获取数据。我正在使用提供商托管的应用程序从主机网站获取数据。我有 2 种调用 2 个单独列表的方法。 我成功地从第一种方法获得了结果,但是当第一种方法执行后调用第二种方法时。我收到超时错误。似乎我不能一个接一个地调用这两种方法。下面是我的代码,如果我遗漏了什么或者是否有任何其他方法可以从多个 SharePoint 列表中获取数据,任何人都可以帮助我。

方法 1:从列表 1 中获取数据

var query = listEndPoint + "/getbytitle('CandidateList')/items?$select=ID,FirstName,MiddleInitial,LastName,EmailAddress,PrimaryPhoneNo,ProfileImage,Address,State,Country,CurrentTitle,CurrentCompany,LastActivityModifiedBy,LastActivityModifiedDate,DeletedStatus&@target='" + hostweburl + "'";

    var getCandidates = function (query, queryCandidateNotes) 
                    {
                    alert('getRequest');
                    var scriptbase = hostweburl + "/_layouts/15/";
                    var deferred = $q.defer();
                    // Load 15hives js files and continue to the successHandler    
                    $.getScript(scriptbase + "SP.Runtime.js",
                        function () {`enter code here`
                            $.getScript(scriptbase + "SP.js",
                                function () {
                                    $.getScript(scriptbase +"SP.RequestExecutor.js",
                                         function () {
                                             var executor = new SP.RequestExecutor(appweburl);
                                             executor.executeAsync({
                                                 url: query,
                                                 method: "GET",
                                                 headers: { "Accept": "application/json; odata=verbose" },
                                                 success: successHandler,
                                                 error: errorHandler
                                             });
                                             //deferred.resolve();
                                         });
                                });
                        });

                    function successHandler(data) {
                        var jsonObject1 = JSON.parse(data.body);

                        deferred.resolve(jsonObject1);

                    }

                    function errorHandler(data, errorCode, errorMessage) {
                        alert('Error1:' + errorMessage + data.body);
                    }
                    // Get 
                    return deferred.promise;

                    //Candidate Details Ends
                };

方法 2:从列表 2 中获取数据

    var queryCandidateNotes = listEndPoint + "/getbytitle('CandidateNotes')/items?$select=Title,CandidateId&@target='" + hostweburl + "'";

 // Get All Candidate Notes
            var getCandidateNotes = function (queryCandidateNotes) {
                alert('getCandidateNotesRequest');
                var scriptbase = hostweburl + "/_layouts/15/";
                var deferred2 = $q.defer();
                // Load 15hives js files and continue to the successHandler    
                $.getScript(scriptbase + "SP.Runtime.js",
                    function () {
                        $.getScript(scriptbase + "SP.js",
                            function () {
                                $.getScript(scriptbase + "SP.RequestExecutor.js",
                                     function () {
                                         var executor = new SP.RequestExecutor(appweburl);
                                         executor.executeAsync({
                                             url: queryCandidateNotes,
                                             method: "GET",
                                             headers: { "Accept": "application/json; odata=verbose" },
                                             success: successHandler,
                                             error: errorHandler
                                         });
                                         //deferred.resolve();
                                     });
                            });
                    });

                function successHandler(data) {
                    var jsonObject2 = JSON.parse(data.body);
                    //var results2 = jsonObject2.d.results;
                    deferred2.resolve(jsonObject2);
                    //alert('2nd success:' + jsonObject2);
                    //return jsonObject2;
                }

                function errorHandler(data, errorCode, errorMessage) {
                    alert('Error2 :' + errorMessage + data.body);
                }
                // Get 
                return deferred2.promise;

};

方法三:在方法一之后调用方法二

   var getRequest = function (query, queryCandidateNotes) {


                var deferred = $q.defer();
                $.when(getCandidates(query, queryCandidateNotes)).then(function (data) {

                    alert('Success1:' + data);

                                           $.when(getCandidateNotes(queryCandidateNotes)).then(function (data1) {
                        deferred.resolve(data);
                        alert('Success2:' + data1);
                    });
                    })
                return deferred.promise;
            };

            return {
                getRequest: getRequest

            };

        }]);
})();

$.when 在这里不合适,利用 $q.all 将多个 promise 组合成一个 promise,当所有输入的 promises 都被解析时,该 promise 被解析 .

示例

app.controller('listController', function ($scope, $q, listService) {
    SP.SOD.executeFunc('SP.RequestExecutor.js', 'SP.RequestExecutor', function () {

        $q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
            $scope.documentsItems = data[0].d.results;
            $scope.sitePagesItems = data[1].d.results;

        });

    });
});

其中 listService 是获取列表项的服务:

app.factory('listService', ['$q', function ($q) {
    var getListItems = function (listTitle) {
        var d = $q.defer();
        JSRequest.EnsureSetup();
        var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
        var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);

        var queryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('" + listTitle + "')/items?@target='" + hostweburl + "'";
        var executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync({
            url: queryUrl,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function(data, textStatus, xhr) {
                d.resolve(JSON.parse(data.body));
            },
            error: function(xhr, textStatus, errorThrown) {
                d.reject(JSON.parse(xhr.body).error);
            }
        });
        return d.promise;
    };

    return {
        getListItems: getListItems
    };
}]);

解决方案说明

Default.aspx

<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
    <meta name="WebPartPageExpansion" content="full" />

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->

    <script type="text/javascript" src="../Scripts/listService.js"></script>
    <script type="text/javascript" src="../Scripts/App.js"></script>

</asp:Content>

<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div ng-app="SPApp" ng-controller="listController">
    </div>
</asp:Content>

App.js

'use strict';

(function() {

    var app = angular.module('SPApp', ['SPApp.services']);

    app.controller('listController', function ($scope, $q, listService) {

        executeOnSPLoaded(function () {
                $q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
                    $scope.documentsItems = data[0].d.results;
                    $scope.sitePagesItems = data[1].d.results;
                });
        });


    });

})();



function executeOnSPLoaded(loaded) {
    JSRequest.EnsureSetup();
    var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
    var scriptbase = hostweburl + "/_layouts/15/";
    $.when(
        //$.getScript(scriptbase + "SP.Runtime.js"),
        $.getScript(scriptbase + "SP.js"),
        $.getScript(scriptbase + "SP.RequestExecutor.js"),
        $.Deferred(function (deferred) {
            $(deferred.resolve);
        })
    ).done(function () {
        loaded();
    });
}

listService.js

'use strict';


angular.module('SPApp.services',[])
.factory('listService', ['$q', function ($q) {
    var getListItems = function (listTitle) {
        var d = $q.defer();
        JSRequest.EnsureSetup();
        var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
        var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);

        var queryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('" + listTitle + "')/items?@target='" + hostweburl + "'";
        var executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync({
            url: queryUrl,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function(data, textStatus, xhr) {
                d.resolve(JSON.parse(data.body));
            },
            error: function(xhr, textStatus, errorThrown) {
                d.reject(JSON.parse(xhr.body).error);
            }
        });
        return d.promise;
    };

    return {
        getListItems: getListItems
    };
}]);