2014-09-06 48 views
1

我寫了這個服務使用無極返回undefined

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

app.service('$SharePointJSOMService', function ($q, $http) { 
    this.getListItems = function ($scope, listTitle) { 
     var deferred = $q.defer(); 
     //First we must call the EnsureSetup method 
     JSRequest.EnsureSetup(); 
     hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); 
     appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]); 
     var restQueryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('" + listTitle + "')/items?$select=Title&@target='" + hostweburl + "'"; 
     var executor = new SP.RequestExecutor(appweburl); 
     executor.executeAsync({ 
      url: restQueryUrl, 
      method: "GET", 
      headers: { "Accept": "application/json; odata=verbose" }, 
      success: function (data, textStatus, xhr) { 
       console.log('call was a success'); 
       console.log(JSON.parse(data.body)); 
       deferred.resolve(JSON.parse(data.body)); 
      }, 
      error: function (xhr, textStatus, errorThrown) { 
       alert('call failed'); 
       alert(textStatus); 
       alert(JSON.stringify(xhr)); 
       deferred.reject(JSON.stringify(xhr)); 
      } 
     }); 
     return deferred; 
    }; 
}); 

我在我的控制器

app.controller('TodoController', function ($scope, $SharePointJSOMService) { 
    $scope.todos = []; 
    var promise = $SharePointJSOMService.getListItems($scope, 'TodoList'); 
    promise.then(function (data) { 
     console.log("came inside the promise success method"); 
     $scope.todos = [];   
     angular.forEach(data.data.d.results, function (todo) { 
      console.log(todo); 
      $scope.todo.push({ 
       text: todo.Title 
      }); 
     }); 
    }, function (data) { 
     console.log("Error " + data); 
    }); 
}); // controller 

在日誌中調用這個服務,我可以看到

call was a success App.js:17 
Object {d: Object} App.js:18 
TypeError: undefined is not a function 
    at new <anonymous> (http://app-6c6f508a56f90c.abhiapps.com/HelloWorld/Scripts/App.js:83:13) 
    at invoke (http://app-6c6f508a56f90c.abhiapps.com/HelloWorld/Scripts/angular.js:3966:17) 

所以服務方法的調用是成功的,我可以看到它打印出正確的結果。但是當我在控制器中調用「promise.then」方法時,我承諾未定義。

回答

2

我認爲你必須回報承諾,而不僅僅是'延期'。

return deferred.promise;