使用RxJS将数据从AngularJS服务返回到控制器 [英] Returning data from AngularJS service to controller with RxJS

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

问题描述

我正在使用Web套接字连接到服务器. 我正在从控制器呼叫服务. 该请求将发送到服务器,响应将返回到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 );    

});

推荐答案

使用 RxJS 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);
      }
  };
});

然后只需订阅消息即可.

Then simply subscribe to the messages.

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服务返回到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆