我有一个封装websocket连接的AngularJS工厂。我希望在我的控制器中使用其中的一些,每个都连接到不同的端点(由personId
指定)
angular.module('personService', ['ngResource']).
factory('Person', function($resource) {
var service = {};
if (service.ws) { return; }
var personId = ??? // This will be different for each person.
var ws = new WebSocket("ws://127.0.0.1:5000/" + personId + "/");
ws.onopen = function() {
console.log("WebSocket opened");
};
ws.onerror = function(err) {
console.log("WebSocket error " + err);
}
ws.onmessage = function(message) {
service.callback(message.data);
};
service.ws = ws;
service.send = function(message) {
service.ws.send(message);
}
service.subscribe = function(callback) {
service.callback = callback;
}
return service;
});
function Ctrl($scope, $timeout, Person) {
$scope.p1 = Person("personId1"); // ??
$scope.p2 = Person("personId1"); // ??
}
答案 0 :(得分:2)
更新 对不起,我实际上误解了你一点。 正常定义Person构造函数,即
function Person(id) {
var ws = new Websocket('some url ' + id);
}
然后注入工厂
app.factory('PersonFactory', function () { return Person; });
然后在您的控制器中
app.controller('MyCtrl', function ($scope, PersonFactory) {
$scope.person1 = new PersonFactory(1);
$scope.person2 = new PersonFactory(2);
}
et voila'。