2

REST API と Angularjs を使用して複数の SharePoint 2013 リストからデータを取得するシナリオがあります。SharePoint リストの 1 つからデータを正常にフェッチできますが、私の要件は、ページの読み込み時に複数のリストからデータをフェッチすることです。プロバイダーがホストするアプリを使用して、ホスト Web からデータを取得しています。2 つの別々のリストを呼び出す方法は 2 つあります。最初のメソッドから正常に結果を取得していますが、最初のメソッドの実行後に 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;

};

方法 3: 方法 1 の後に方法 2 を呼び出す

   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

            };

        }]);
})();
4

1 に答える 1

3

$.whenはここでは適切ではありません。複数の promise を単一の promise に結合し、すべての入力 promise が解決されたときに解決されることを$q.all利用します。

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
    };
}]);
于 2016-01-11T13:13:51.190 に答える