Node.js 用Angular向NodeJS、Express发送请求
我正在用angluar和nodejs创建第一个应用程序,还有express framework,所以我有几个问题Node.js 用Angular向NodeJS、Express发送请求,node.js,angularjs,post,service,express,Node.js,Angularjs,Post,Service,Express,我正在用angluar和nodejs创建第一个应用程序,还有express framework,所以我有几个问题 如何将数据(json)发布到服务器-如何在post请求中将json传递到服务器,现在可以工作,但get请求是否尝试调用appName://games/games\u id/results?priority=0&priority=0& 当我返回json时,如何重定向到其他角度视图,以便他的控制器能够看到从服务器返回的json controllers.js $scope.generate
$scope.generate = function() {
Generator.gPriority({gameId: $routeParams.gameId, priority: $scope.priority}, function() {
$location.path("/games"); //redirect when get json from server to other view/controller/partias and process json ...show json in table
});
};
service.js
var appServices = angular.module('appServices', ['ngResource']);
appServices.factory('Generator', ['$resource',
function($resource){
return $resource('games/:gameId/results', {}, {
gRandom: {method:'GET', params:{gameId:''}, isArray:true},
gPriority: {method: 'POST', params:{gameId:'',priority: '@priority'}}
});
}
]);
server.js
app.post('/games/:id/results', generator.gWithPriority);
generator.js
exports.gWithPriority = function(req, res) {
var priority = req.body;
console.log('Game priority: ' + JSON.stringify(priority));
res.json({
"numbers": [
[[8,7,6,5,4,3,2,1],[1,2]],
[[3,2,3,4,5,6,7,8],[1,3]],
[[4,2,3,4,5,6,7,8],[1,2]]
]
});
};
对不起,我的英语不好。我可以帮你解决第二个问题。如果要在控制器之间共享数据,请使用服务。例如:
angular.module('myApp').factory('DataService', function(){
var data = {};
return {
getData: function() { return data; },
setData: function(newData) { data = newData; }
};
});
在Generator.gPriority(…)
的回调中使用setter,并在新视图的控制器中使用getter。这样,您可以将数据从一个控制器传递到服务,然后从其他控制器检索该数据