我使用此服务,它使用回调异步返回学生列表:
studentModule.factory('StudentService', function (DB_URL) {
return {
getAllStudents: function (callback) {
var Datastore = require('nedb'),
path = require('path');
db = {};
db.students = new Datastore({
filename: DB_URL + '/students.db',
autoload: true
});
db.students.find({}, function (err, stds) {
callback(stds);
});
}; //end return
我在控制器中使用它的旧方法:
StudentService.getAllStudents(function(sts) {
$scope.students = sts;
$scope.$apply();//notify angular about the change
});
这适合我,但现在我想使用一些最佳实践。我需要在进入控制器之前解决路由中的结果,这就是我所做的:
.state('payment', {
url: '/payment',
templateUrl: 'frontend/components/payment/views/payment.html',
controller: 'PaymentController',
resolve: {
students: function (StudentService, $q) {
var defer = $q.defer();
defer.promise.then(function () {
StudentService.getAllStudents(function (sts) {
alert(JSON.stringify(sts));
return sts;
});
})
defer.resolve();
}
}
})
警报正在从路径成功返回数据,但不是从控制器返回 - 我在控制器中得到未定义:
paymentModule.controller('PaymentController', function($scope,students) {
alert(JSON.stringify(students));
任何帮助将不胜感激!
答案 0 :(得分:2)
您应该始终返回一个解决函数的承诺,并且在创建自己的承诺时,您应该使用您需要传递的数据来解决它。
.state('payment', {
url: '/payment',
templateUrl: 'frontend/components/payment/views/payment.html',
controller: 'PaymentController',
resolve: {
students: function (StudentService, $q) {
var defer = $q.defer();
//defer.promise.then(function () {
StudentService.getAllStudents(function (sts) {
//alert(JSON.stringify(sts));
//return sts;
defer.resolve(sts);
});
//})
//defer.resolve();
return defer.promise
}
}
})