angular-socket-io icon indicating copy to clipboard operation
angular-socket-io copied to clipboard

doesn't remove or empty array on listener after change route

Open essivision opened this issue 8 years ago • 4 comments

Hi, I defined a service like this:

'use strict';

app.factory('mySocket', function(socketFactory) {
    return socketFactory({
        ioSocket: io.connect(':3001',{forceNew: true})
    });
});

and in controller:

app.controller('ChatCtrl',function($scope, mySocket,$rootScope) {
    $scope.arr = []; 
    $scope.arr.length = 0; 
    $scope.currentChannel = 1;

 Restangular.all('chat/message/').getList().then(function (data) {
            $scope.arr[$scope.currentChannel] =data;

  mySocket.on('connect', function () {
        console.log('CONNECT');

        mySocket.on('messages.new', function (data) {
             var tmp = data;
                   tmp.timestamp = data.timestamp.date;
             $scope.arr[data.thread].push(tmp);
        })
})

when I refresh page all things is okay, but when I switch to another page and come back to chat page $scope.arr not null and last data array in listener is exist.

What should I do for null array after come back to chat page (just on listener block)?

essivision avatar Feb 26 '17 14:02 essivision

I have problem like this ^ I have controller with chatSocket handler: chatSocket.on('message', (data) => console.log); First time console.log work only once. But when i change routes, e.g. /chat -> /main -> /chat Now my handler work TWICE. Should i use chatSocket.removeAllListeners() before enter the /chat or ... ?

frizar avatar Mar 16 '17 15:03 frizar

I just install example from angular-socket-io-seed and i have same problem.

frizar avatar Mar 16 '17 15:03 frizar

@frizar, Do you find any solutions?

essivision avatar Apr 13 '17 13:04 essivision

@essivision, I just remove listeners before scope destroyed on state change. In angular 1.5+ i use: this.$onDestroy hook (https://docs.angularjs.org/guide/component) In this hook i just write chatSocket.removeListener('message');

frizar avatar Apr 13 '17 20:04 frizar