简体   繁体   中英

How to re-initialize the service or factory in angular js

I want to re-initialize the service after logout

var app = angular.module('plunker', []);

app.controller('ControllerA', ['$scope','serviceA',function($scope, serviceA)     {

    $scope.initializeA = function(){          
        serviceA.initialize("Chris");
    };  
}]);

and service is

app.service('serviceA',function(){
 var service={};
 service.initialize=function(){}
});

I have many services like above. I want to clear all data inside these services when I logout.

Please tell me the best way to do it.

I can think of few ways to do this but let's go with one:

You can subscribe to the $destroy event that occurs when a controller is about to be, well, destroyed. When this happen you can call the service you have injected to your controller and initialize it. This will ensure all services that were used are now cleared (assuming that your logout is another state in your app, using ui-router for example in which all the components that are not in the current state are destroyed).

There are many ways that you can achieve what you want.

Since you are saying that is on logout that you want to clear the data inside of the service and you are not saying nothing about redirect's or destruction of the controllers. I wil sugest a simple implementation of $scope.$emit and $rootScope.$on .

So on your authentication Controller on logout your should do something like this:

.controller('authenticationCtrl',[...
    //request for logout
    ...
        //On logout Success
        $scope.$emit('logout');
}]);

And in your Service you will receive it like this:

...
.service('serviceA', ['$rootScope',function($rootScope){
    $rootScope.$on('logout', function () {
        //TODO: clear all the data you want
    });
}

Another option, is if the module are being constructed again (reload/redirect) you can use the run functionality to set back the initial data:

angular.module('plunker')
.run(
    function (serviceA) {

        // serviceA.initialize()
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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