保存后客户端未收到Controller发送的新消息

时间:2017-01-25 08:17:53

标签: angularjs spring ionic-framework jhipster

我有一个用jhipster 3.12.2生成的项目,我试图在我将它保存到数据库后通过我的控制器的websockets发送一条警报消息。 可以从jhipster前端(创建新实体)或从发送HTTP POST的移动应用程序调用RestController。

出于某种原因,我的客户端(使用离子和角度生成的移动应用程序)没有收到任何新消息。我的代码出了什么问题?

@RestController
@RequestMapping("/api")
public class AlarmResource {

private final Logger log = LoggerFactory.getLogger(AlarmResource.class);

@Inject
private AlarmService alarmService;

@Inject
SimpMessageSendingOperations messagingTemplate;

@PostMapping(value = "/alarms")
@Timed
@CrossOrigin
@Secured({AuthoritiesConstants.ALARM, AuthoritiesConstants.ADMIN, AuthoritiesConstants.EDITOR})
public ResponseEntity<Alarm> createAlarm(@RequestBody Alarm alarm) throws URISyntaxException {
    log.debug("REST request to save Alarm : {}", alarm);
    if (alarm.getId() != null) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("alarm", "idexists", "A new alarm cannot already have an ID")).body(null);
    }
    if(alarm.getTimestamp_ms() == null) {
        BigDecimal now = new BigDecimal(System.currentTimeMillis());
        alarm.setTimestamp_ms(now);
    }
    Alarm result = alarmService.save(alarm);

    System.out.println("Sending ne alarm message");
    String dest = "/topic/alarmactivity";
    messagingTemplate.convertAndSend(dest, result);


    return ResponseEntity.created(new URI("/api/alarms/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert("alarm", result.getId().toString()))
        .body(result);
}

AlarmMessageService:

@Controller
public class AlarmMessageService  {

private static final Logger log = LoggerFactory.getLogger(AlarmMessageService.class);


private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

@SubscribeMapping("/topic/alarmactivity")
@SendTo("/topic/alarmtracker")
public Alarm sendAlarm(@Payload Alarm newAlarm, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
    log.debug("Sending user tracking data {}", newAlarm);
    return newAlarm;
}
}

客户端的tracker-service.js:

(function() {
'use strict';
/* globals SockJS, Stomp */

angular
    .module('exampleApp')
    .factory('ExAlarmTrackerService', ExAlarmTrackerService);

ExAlarmTrackerService.$inject = ['$rootScope', '$window', '$localStorage', '$http', 'API_URL','$q', 'AuthServerProvider', '$stomp'];

function ExAlarmTrackerService ($rootScope, $window, $localStorage, $http, API_URL, $q, AuthServerProvider, $stomp) {

    var stompClient = null;
    var subscriber = null;
    var listener = $q.defer();
    var connected = $q.defer();
    var alreadyConnectedOnce = false;

    var service = {
        connect: connect,
        disconnect: disconnect,
        receive: receive,
        sendActivity: sendActivity,
        subscribe: subscribe,
        unsubscribe: unsubscribe
    };

    return service;

    function connect () {
        //building absolute path so that websocket doesnt fail when deploying with a context path
        var loc = $window.location;
        var url = API_URL + 'websocket/tracker';
        var authToken = AuthServerProvider.getToken();
        if(authToken){
            url += '?access_token=' + authToken;
        }
        var socket = new SockJS(url);
        stompClient = Stomp.over(socket);
        var stateChangeStart;
        var headers = {};
        stompClient.connect(headers, function() {
            connected.resolve('success');
            //sendActivity();
            if (!alreadyConnectedOnce) {
                stateChangeStart = $rootScope.$on('$stateChangeStart', function () {
                    //sendActivity();
                    console.log("statechange");
                });
                alreadyConnectedOnce = true;
            }
        });
        $rootScope.$on('$destroy', function () {
            if(angular.isDefined(stateChangeStart) && stateChangeStart !== null){
                stateChangeStart();
            }
        });
    }

    function disconnect () {
        if (stompClient !== null) {
            stompClient.disconnect();
            stompClient = null;
        }
    }

    function receive () {
        return listener.promise;
    }

    function sendActivity() {
        if (stompClient !== null && stompClient.connected) {
            stompClient
                .send('/topic/activity',
                {},
                angular.toJson({'page': $rootScope.toState.name}));
        }
    }

    function subscribe () {
        connected.promise.then(function() {
            subscriber = stompClient.subscribe('/topic/alarmtracker', function(data) {
                listener.notify(angular.fromJson(data.body));
            });
        }, null, null);
    }

    function unsubscribe () {
        if (subscriber !== null) {
            subscriber.unsubscribe();
        }
        listener = $q.defer();
    }


}
})();

在我的controller.js中:

 ExAlarmTrackerService.receive().then(null, null, function(activity) {
    console.log(activity);
 });

1 个答案:

答案 0 :(得分:0)

我的移动应用程序没有连接到正确的路径,所以在修复后一切正常。