简体   繁体   English

Angular中的路线更改后Socket.io停止工作

[英]Socket.io stops working after route change in Angular

Poblem Poblem

I have a simple Angular app with 3 routes: r1, r2, r3. 我有一个简单的Angular应用,其中包含3条路线:r1,r2,r3。 The r1's controller has listeners to socket events. r1的控制器具有套接字事件的侦听器。 This is the first route that gets loaded on starting the app. 这是启动应用程序时加载的第一条路线。 Things work fine when the app is started. 启动应用程序后,一切正常。 However, when I navigate to r2/r3 and then back to r1, sockets stop working. 但是,当我导航到r2 / r3然后又回到r1时,套接字停止工作。 There is no error in the console. 控制台中没有错误。

Code

app.js app.js

var host = "http://myhost.com";
var socket = io(host + ':3000');

angular
    .module('myApp', [
        'ngRoute'
    ])
    .config(function ($routeProvider) {
        $routeProvider
                .when('/', {
                    templateUrl: 'views/r1.html',
                    controller: 'r1Ctrl'
                })
                .when('/r2', {
                    templateUrl: 'views/r2.html',
                    controller: 'r2Ctrl'
                })
                .when('/r3', {
                  templateUrl: 'views/r3.html',
                  controller: 'r3Ctrl'
                })
                .otherwise({
                    redirectTo: '/'
                });
    });

r1Ctrl.js r1Ctrl.js

angular.module('myApp')
    .controller('r1Ctrl', function ($scope) {
        // Listeners
        socket.on('event1', function (data) {
            $scope.$apply(function () {
                ...
            });
        });
        ...
});

Even if you leave r1, the socket listener remains registered. 即使您离开r1,套接字侦听器仍保持注册状态。 When you visit r1 again, another listener is registered for the same event. 当您再次访问r1时,将为同一事件注册另一个侦听器。 The only explanation of your problem is that your callback is not built with that fact in mind and fails to do the work if it has already been done. 对您的问题的唯一解释是,您的回调并不是在考虑这一事实的情况下构建的,并且如果已经完成,则无法执行该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM