Returning data from AngularJS service to controller with RxJS

二次信任 提交于 2019-12-13 03:47:07

问题


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.

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

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

controller.js

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

});

回答1:


Build the service with 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);
      }
  };
});

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

Clients can subscribe to messages with DataService.subscribe.



来源:https://stackoverflow.com/questions/47917329/returning-data-from-angularjs-service-to-controller-with-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!