gpt4 book ai didi

javascript - AngularJS : wait for function to respond in factory. 用于异步通信

转载 作者:行者123 更新时间:2023-12-03 06:40:51 24 4
gpt4 key购买 nike

我有一个将搜索词传递给工厂的按钮:

<button type="button" class="btn btn-default btn-sm" ng-click="searchFactory(search_name)">Search</button>

工厂调用返回 JSON 的 websocket。

var angularjsapp = angular.module('graphApp', ['ngAnimate', 'ui.bootstrap']);
angularjsapp.factory('searchFactory', function() {
//return $resource('friends.json');
return {
myfunc:function(search_name){
console.log('ok')
keyword_type = 1
WebSocketTest(search_name,keyword_type)

}
}
});

angularjsapp.controller('AccordionDemoCtrl', function($scope,searchFactory) {
$scope.count = 0;
$scope.namesPerPage = 10
$scope.currentPage = 1;
$scope.searchFactory = searchFactory.myfunc;
});

然后我想将该 JSON 显示回 html。为此我需要两件事。首先等待 websocket 函数返回 JSON,然后在 Controller 中获取该值以显示回来。有什么想法可以做到吗?

最佳答案

好吧,你需要使用一个 Promise 来等待 websocket 返回数据。尝试这样的事情

angularjsapp.controller('AccordionDemoCtrl', function($scope,searchFactory) {
$scope.count = 0;
$scope.namesPerPage = 10
$scope.currentPage = 1;
$scope.searchFactory = function(search_name){
searchFactory.myfunc(search_name).then(function(response){
//success `enter code here`
},function(){
//error`enter code here`
})
}
});

//工厂

angularjsapp.factory('searchFactory', function($q) { 
return {
myfunc:function(search_name){
console.log('ok')
keyword_type = 1;
return $q(function(resolve, reject) {
setTimeout(function() {
if (WebSocketTest(search_name,keyword_type)) {
resolve('sucess result');
} else {
reject('error result');
}
}, 1000);
});
}
}
});

关于javascript - AngularJS : wait for function to respond in factory. 用于异步通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968804/

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