Answer the question
In order to leave comments, you need to log in
How to make an asynchronous Websocket in Angular js?
Hello. There is this code:
.run(["$rootScope", "$cacheFactory", "$websocket", function($rootScope, $cacheFactory, $websocket) {
$rootScope.cache = $cacheFactory('PJ');
$rootScope.ws = $websocket('ws://localhost');
}])
.controller('profileInfo', ['$scope', '$http', '$cookieStore', 'Websocket', '$rootScope', function($scope, $http, $cookieStore, Websocket, $rootScope) {
var subject = 'user';
var param = '"user": {"login": "'+ $cookieStore.get('uname') +'"}';
var method = 'get_info';
Websocket.get(param, subject, method)
.then(function(data) {
alert(data);
});
var subject = 'user';
var param = '"user": {"login": "'+ $cookieStore.get('uname') +'"}';
var method = 'get_projects';
$scope.keys = {};
Websocket.get(param, subject, method)
.then(function(data) {
alert(data);
});
}])
.factory('Websocket',['$rootScope', '$q', function($rootScope, $q) {
function randomId(){
var s ='', abd ='abcdefghijklmnopqrstuvwxyz0123456789', aL = abd.length;
while(s.length < '40')
s += abd[Math.random() * aL|0];
return s;
}
var get = function(param, subject, method) {
var id = randomId();
var deferred = $q.defer();
$rootScope.ws.send('{"id": "' + id + '", "type": "request", "version": "v.2.0", "method": "' + method + '", "subject": "' + subject + '", "parameters": {' + param + '}}');
$rootScope.ws.onMessage(function (message) {
deferred.resolve(message.data);
});
return deferred.promise;
}
return {
get: get
};
}]);
var subject = 'user';
var param = '"user": {"login": "'+ $cookieStore.get('uname') +'"}';
var method = 'get_info';
Websocket.get(param, subject, method)
.then(function(data) {
alert(data);
});
var subject = 'user';
var param = '"user": {"login": "'+ $cookieStore.get('uname') +'"}';
var method = 'get_projects';
$scope.keys = {};
Websocket.get(param, subject, method)
.then(function(data) {
alert(data);
});
Answer the question
In order to leave comments, you need to log in
// тут вешается слушатель на все сообщения из сокета, на сервер передается id,
// если он возвращается нужно его проверить.
$rootScope.ws.onMessage(function (message) {
deferred.resolve(message.data);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question