简体   繁体   English

如何防止角度提供程序多次加载

[英]How prevent angular provider loads many times

I have a provider (I also tried with controller with same results). 我有一个提供程序(我也尝试了具有相同结果的控制器)。 This is my code: 这是我的代码:

.provider('socketio', function() {
    this.socket = io.connect("//localhost);
    console.log("LISTENING...");

    this.$get = function() { [...] }
});

I'm injecting this way: 我以这种方式注入:

.controller('HeaderCtrl', function($rootScope, $scope, login) { [...] }

and

.factory('login', function($location, socketio, $rootScope) {

    // socketio operations

})

But in my console, I see two LOGS, infact, i have two socketio listening each of them with a event listener. 但是实际上,在控制台中,我看到两个LOGS,我有两个socketio用一个事件监听器监听它们。 My console is full with doubled messages. 我的控制台已满,消息翻倍。

听留言

Any hint? 有什么提示吗? Thanks. 谢谢。

Providers are meant to be "factories", hence they must not directly build the service they provide but just offer a get method to be called by Angular to get a factory. 提供者是“工厂”,因此他们不能直接构建提供的服务,而只能提供Angular调用的get方法来获得工厂。 Their use is clearly described in the Angular documentation . Angular 文档中明确描述了它们的用法。 So maybe you should move the io.connect call inside the $get method. 因此,也许您应该在$get方法内移动io.connect调用。

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

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