我会用一个简单的例子来解释我的问题。
Parse.initialize("nlxy5xYYZQ1fLfFkzcyLHOifkie1dOU0ZSxoxw1w", "IRBJO7nyd1vQquhMvnyMd298ZVJ0qWg1AjxBY5nr");
var People = Parse.Object.extend("People");
var app = angular.module('app', []);
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
$scope.people = PeopleService.getPeople();
}]);
app.service("PeopleService", function(){
var people = null;
return {
getPeople: function(){
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
return people;
},
error: function (error) {
console.error("Error: " + error.code + " " + error.message);
}
});
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<script src="https://www.parsecdn.com/js/parse-1.3.2.min.js"></script>
<div ng-app="app">
<ul ng-controller="MyCtrl">
<li ng-repeat="person in people">{{person}}</li>
</ul>
</div>
&#13;
现在,当然,当Parse返回数据时,控制器中的范围不会更新。 如何使这项服务正常运作?
答案 0 :(得分:5)
正如@james所述,使用$ q服务中的promises是您正在寻找的。以下是您的例子。
getPeople: function(){
var deferred = $q.defer();
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
deferred.resolve(people);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
这会返回一个你可以像这样使用的承诺
$scope.people = PeopleService.getPeople();
或
$scope.people = PeopleService.getPeople()
.then(function(people) {
//modify data as necessary
return people
}, function(reason) {
alert('Failed: ' + reason);
}
);