如何在 angular 服务中使用 $on? [英] How do i use $on in a service in angular?

查看:30
本文介绍了如何在 angular 服务中使用 $on?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够让控制器使用 $on 监听器使用 $scope.$on.

i have been able to get controller to use the $on listener with $scope.$on.

但我没有看到任何关于如何让服务监听事件的文档.

but i don't see any documentation on how to get services to listen for events.

我尝试了 $rootScope.$on,但它只允许一个监听器.我想要多个服务中的侦听器,无论它们的父控制器是否在范围内.

I tried $rootScope.$on, but that only allows one listener. i want listeners in multiple services regardless of whether their parent controllers are in scope or not.

推荐答案

经过大量试验后发现,可以用最少的代码将事件发送到服务.

after experimenting a fair bit it turns out that getting events to the service can be done with minimal code.

示例服务代码如下,以防其他人遇到此问题.

sample service code follows in case anyone else runs into this.

样本在获取到各自的广播后,将服务模型保存并恢复到本地存储

The sample saves and restores the service model to local storage when it gets the respective broadcasts

app.factory('userService', ['$rootScope', function ($rootScope) {

    var service = {

        model: {
            name: '',
            email: ''
        },

        SaveState: function () {
            sessionStorage.userService = angular.toJson(service.model);
        },

        RestoreState: function () {
            service.model = angular.fromJson(sessionStorage.userService);
        }
    }

    $rootScope.$on("savestate", service.SaveState);
    $rootScope.$on("restorestate", service.RestoreState);

    return service;
}]);

这篇关于如何在 angular 服务中使用 $on?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆