我有一个我希望重用的CRUD操作,所以我有一个工厂通过$ routeProvider / resolve传递给控制器。
但是我看到控制器在工厂的GET请求返回之前解析。
如何设置promises以便$ routeProvider不会将undefined
传递给控制器?
我的例子:
angular
.module('app',['ngRoute'])
.config(config)
.controller('appController', appController)
.factory('appFactory', appFactory);
function config($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'template.html',
controller: 'appController',
resolve: {
server_stuff: function(appFactory){
// logging
console.log('appFactory.serverReponse = '+ appFactory.serverResponse() );
return appFactory.serverResponse();
}
}
});
}
function appController( $scope, server_stuff ){
$scope.content = server_stuff;
// logging
console.log('server_stuff = '+server_stuff);
}
function appFactory($http){
var i = 1;
var appFactory = {
serverResponse: serverResponse
};
// logging
console.log('Factory execution');
return appFactory;
function serverResponse(){
// logging
console.log('pre-GET ' + i);
$http.get('/endpoint/')
.success(function(data){
// logging
console.log('GET is done ' + i);
i++
return data;
});
}
}
记录输出:
'Factory execution'
'pre-GET 1'
'appFactory.serverReponse = undefined'
'pre-GET 1'
'server_stuff = undefined'
'GET is done 1'
'GET is done 2'
我的更改:
路由器解析:我选择传递$ http函数并稍后执行
return appFactory.server; // no paren
工厂简化:
return $http.get('/endpoint/);
controller:利用注入的工厂作为服务器调用...
function appController( $scope, server_stuff ){
server_stuff().success( function(data){
// do stuff with the server info
});
答案 0 :(得分:1)
正如@KevinB所说,在工厂使用$ http电话应该看看:
在您的工厂
function serverResponse(){
// logging
console.log('pre-GET ' + i);
return $http.get('/endpoint/')
.success(function(data){
// logging
console.log('GET is done ' + i);
i++
});
}
在控制器中:
MyFactory.serverResponse().success(function(data){
//your controller handling of the data.
});
在路由器解析:
resolve: {
server_stuff: function(appFactory){
return appFactory.serverResponse();
}
}
您的路由器解析将自行处理$ http呼叫的成功。