服务返回到控制器

服务返回到控制器

本文介绍了使用 RxJS 将数据从 AngularJS 服务返回到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用网络套接字连接到服务器.我正在从控制器调用服务.请求将发送到服务器,响应返回到 app.js 文件中的服务.

I am using web socket to connect to server.I am calling a service from controller.The request is going to server and response is coming back to service which is in app.js file.

现在我需要控制器文件中的响应.

Now I need the response in controller file.

任何人都可以帮助我如何将响应从 app.js 发送到发出请求的控制器.

Can any one help me how to send the response from app.js to controller from where the request is made.

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;
}])

controller.js

app.controller('myController', function($scope, $state, $rootScope,MyService) {
  $scope.currentTemp = MyService.getTemp('requestString');
 console.log( $scope.currentTemp );

});

推荐答案

使用 Angular 的 RxJS 扩展.

<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 订阅消息.

Clients can subscribe to messages with DataService.subscribe.

这篇关于使用 RxJS 将数据从 AngularJS 服务返回到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:10