简体   繁体   English

如何在角度js中重新初始化服务或工厂

[英]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. 您可以订阅当控制器即将被销毁时发生的$ destroy事件。 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). 这将确保现在清除所有使用的服务(假设您的注销是应用程序中的另一个状态,使用ui-router ,例如,其中所有未处于当前状态的组件都被销毁)。

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 . 我将获得$scope.$emit的简单实现$scope.$emit$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()
    });

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

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