我正在使用Web套接字连接到服务器。 我正在从控制器调用服务。 请求将转到服务器,响应将返回到app.js文件中的服务。
现在我需要控制器文件中的响应。
任何人都可以帮助我如何将响应从app.js发送到发出请求的控制器。
app.factory('MyService', ['$rootScope', function($rootScope) {
var Service = { };
// Create our websocket object with the address to the websocket
var ws = new WebSocket("Server_URL");
ws.onopen = function(){
console.log("Socket has been opened!");
};
ws.onmessage = function(message) {
listener(message.data);
};
function sendRequest(request) {
console.log('Sending request:', request);
ws.send(request);
}
function listener(data) {
var messageObj = data;
console.log("Received data from websocket: ", messageObj);
}
Service.getTemp = function(request) {
sendRequest(request);
}
return Service;
}])
app.controller('myController', function($scope, $state, $rootScope,MyService) {
$scope.currentTemp = MyService.getTemp('requestString');
console.log( $scope.currentTemp );
});
答案 0 :(得分:1)
使用RxJS Extensions for Angular构建服务。
<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);
app.factory("DataService", function(rx) {
var subject = new rx.Subject();
// Create our websocket object with the address to the websocket
var ws = new WebSocket("Server_URL");
ws.onmessage = function(message) {
subject.onNext(message);
};
return {
subscribe: function (o) {
return subject.subscribe(o);
}
};
});
然后只需订阅消息。
app.controller('displayCtrl', function(DataService) {
var $ctrl = this;
var subscription = DataService.subscribe(function onNext(message) {
$ctrl.message = message;
});
this.$onDestroy = function() {
subscription.dispose();
};
});
客户可以使用DataService.subscribe
订阅邮件。