de-*_*ged 39 javascript http angularjs
我试图了解Angular中工厂和服务的概念.我在控制器下面有以下代码
init();
function init(){
$http.post('/services', {
type : 'getSource',
ID : 'TP001'
}).
success(function(data, status) {
updateData(data);
}).
error(function(data, status) {
});
console.log(contentVariable);
};
function updateData(data){
console.log(data);
};
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常.但是当我将$ http服务转移到工厂时,我无法将数据返回给控制器.
studentApp.factory('studentSessionFactory', function($http){
var factory = {};
factory.getSessions = function(){
$http.post('/services', {
type : 'getSource',
ID : 'TP001'
}).
success(function(data, status) {
return data;
}).
error(function(data, status) {
});
};
return factory;
});
studentApp.controller('studentMenu',function($scope, studentSessionFactory){
$scope.variableName = [];
init();
function init(){
$scope.variableName = studentSessionFactory.getSessions();
console.log($scope.variableName);
};
});
Run Code Online (Sandbox Code Playgroud)
使用工厂是否有任何优势,因为$ http甚至可以在控制器下工作
Bri*_*sio 91
将studentSessions
服务移出控制器的目的是实现关注点分离.您的服务工作是了解如何与服务器通信,控制器的工作是在视图数据和服务器数据之间进行转换.
但是你混淆了你的异步处理程序以及返回什么.当稍后收到数据时,控制器仍然需要告诉服务该做什么...
studentApp.factory('studentSession', function($http){
return {
getSessions: function() {
return $http.post('/services', {
type : 'getSource',
ID : 'TP001'
});
}
};
});
studentApp.controller('studentMenu',function($scope, studentSession){
$scope.variableName = [];
var handleSuccess = function(data, status) {
$scope.variableName = data;
console.log($scope.variableName);
};
studentSession.getSessions().success(handleSuccess);
});
Run Code Online (Sandbox Code Playgroud)
小智 10
第一个答案很棒,但也许你可以理解这个:
studentApp.factory('studentSessionFactory', function($http){
var factory = {};
factory.getSessions = function(){
return $http.post('/services', {type :'getSource',ID :'TP001'});
};
return factory;
});
Run Code Online (Sandbox Code Playgroud)
然后:
studentApp.controller('studentMenu',function($scope, studentSessionFactory){
$scope.variableName = [];
init();
function init(){
studentSessionFactory.getSessions().success(function(data, status){
$scope.variableName = data;
});
console.log($scope.variableName);
};
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63801 次 |
最近记录: |