我已写过这项服务
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”方法时,我得到了未定义的承诺。
答案 0 :(得分:2)
我认为你必须退还承诺,而不仅仅是'延期'。
return deferred.promise;