gpt4 book ai didi

javascript - 已声明工厂中的问题 : AngularJs

转载 作者:行者123 更新时间:2023-12-02 17:45:14 26 4
gpt4 key购买 nike

var app = angular.module('app',[]);

//in the html, the following 2 files are attached.
// <script src="lib/sockjs-0.3.4.min.js"></script>
// <script src="lib/vertxbus.min.js"></script>

app.factory('serverData',function(){
var eb = new vertx.EventBus('http://xxx.xxx.xxx.xxx');
var x = {};
eb.send( "com.find.web.ed",{"Em":'user@find.com',"Pw":'123'},
function(reply){
x = reply;
});
var fact = {};
fact.getData = function(){
return x;
};

return fact;
});

app.controller('mainController',function($scope,serverData){

});

在上面的代码中,我试图声明一个工厂来从顶点服务器获取数据。它不起作用,有人可以帮忙吗?

在 Controller 中使用时效果良好。请参阅代码。

var app = angular.module('app',[]);

app.controller('mainController',function($scope,$log){
$rootScope.user = {user :'user@find.com',password :'123'};
$rootScope.reply = {};

$scope.eb = new vertx.EventBus('http://100.100.100.100:8000');

$scope.loginFunction = function(){
$scope.eb.send( "com.find.web.ed",
{"Em":$scope.user.user,"Pw":$scope.user.password},
function(reply){
$rootScope.reply = reply;
$log.warn($rootScope.reply);
}
);
}
});

最佳答案

你的工厂代码只会获取一次数据,并且无法响应 Controller 。我认为您可能正在寻找类似的东西,而不是每次调用 send() 并且 Controller 提供回调...

var app = angular.module('app',[]);

app.factory('serverData', function(){
var eb = new vertx.EventBus('http://xxx.xxx.xxx.xxx');
var fact = {};

fact.getData = function(user, password, callback){
// call send and pass it the callback function
eb.send( "com.find.web.ed",
{"Em": user,"Pw": password},
callback
);
};

return fact;
});

app.controller('mainController', function($scope, serverData){
$scope.user = {user :'user@find.com',password :'123'};
$scope.reply = {};

serverData($scope.user.user, $scope.user.password, function (reply) {
$scope.reply = reply;
// might need $scope.$apply() here
});
});

您还可以通过 $q promise 来做到这一点...

var app = angular.module('app',[]);

app.factory('serverData', function($q){
var eb = new vertx.EventBus('http://xxx.xxx.xxx.xxx');
var fact = {};

fact.getData = function(user, password){
var deferred = $q.defer();
// call send and pass it the callback function
eb.send( "com.find.web.ed",
{"Em": user,"Pw": password},
function (reply) {
deferred.resolve(reply);
}
// also should reject on error
);
return deferred.promise;
};

return fact;
});

app.controller('mainController', function($scope, serverData){
$scope.user = {user :'user@find.com',password :'123'};
$scope.reply = {};

serverData($scope.user.user, $scope.user.password)
.then(function (reply) {
$scope.reply = reply;
});
});

关于javascript - 已声明工厂中的问题 : AngularJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21822294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com