var app = angular.module('myApp', [])
.factory('MyService', ['$q', function($q) {
// We return this object to anything injecting our service
var Service = {};
// Keep all pending requests here until they get responses
var callbacks = {};
// Create a unique callback ID to map requests to responses
var currentCallbackId = 0;
// Create our websocket object with the address to the websocket
var ws = new WebSocket("wss://echo.websocket.org");
ws.onopen = function(){
console.log("Socket has been opened!");
};
ws.onmessage = function(message) {
listener(message);
};
function sendRequest(request, callback) {
var defer = $q.defer();
var callbackId = getCallbackId();
callbacks[callbackId] = {
time: new Date(),
cb:defer
};
request.callback_id = callbackId;
console.log('Sending request', request);
ws.send(JSON.stringify(request));
if(typeof callback == 'function') {
defer.promise.then(function(data) {
callback(null, data);
},
function(error) {
callback(error, null);
});
}
return defer.promise;
}
function listener(data) {
var messageObj = data;
console.log("Received data from websocket: ", messageObj);
// If an object exists with callback_id in our callbacks object, resolve it
if(callbacks.hasOwnProperty(messageObj.callback_id)) {
console.log(callbacks[messageObj.callback_id]);
$rootScope.$apply(callbacks[messageObj.callback_id].cb.resolve(messageObj.data));
delete callbacks[messageObj.callbackID];
}
}
// This creates a new callback ID for a request
function getCallbackId() {
currentCallbackId += 1;
if(currentCallbackId > 10000) {
currentCallbackId = 0;
}
return currentCallbackId;
}
// Define a "getter" for getting customer data
Service.getCustomers =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.