Pregunta

I want to use a dependency in listener but the websocket was undefined

$rootScope.$on('websocket.connected', function() {
    $websocket.request(.....).then();
});

and a want to call a service method (who depend on asyncron method) when it ready

app.controller('MyCtrl', function(myServ, $log) {
    myServ.getInfos();
});

thank you.

Code in jsfiddle http://jsfiddle.net/8DHfY/3/ or here

var app = angular.module('myApp', ['myServ'])
.config(['$websocketProvider', function ($websocketProvider) {
    $websocketProvider.setHost('ws://echo.websocket.org/');
}])
.controller('MyCtrl', function(myServ, $log) {
    $log.log('I want to call myServ.getInfos() from a controler');
});

angular.module('myServ', ['websocket']).service('myServ', ['$log', '$rootScope', '$websocket', function($log, $rootScope, $websocket) {

    $log.error('websocket is %o ... ???', $websocket); // return undefined

    $rootScope.$on('websocket.connected', function() {
        $log.error('websocket is still %o', $websocket); // return undefined
    });

    return {
        getInfos: function() {
            $websocket.request(JSON.stringify({'key': 'value'}));
        }
    };
}]);

angular.module('websocket', []).provider('$websocket', [function() {

    var _this = this;

    _this.host = '';
    _this.connection = null;

    _this.setHost = function(host) {
        this.host = host;
        return this;
    };

    _this.request = function(request) {
        //request method for websocket
    };

    this.$get = ['$log', '$rootScope', function($log, $rootScope) {

        _this.connection = new WebSocket(this.host);
        _this.connection.onopen = function(){
            $log.log('Websocket connected to %s', _this.host);
            $rootScope.$emit('websocket.connected');
        };
    }];
}]);
¿Fue útil?

Solución

Providers invoke the $get function upon injection and use the singleton of whatever is returned from that function.

This means since you do not return anything from the $get function, it uses undefined.

Here's an updated fiddle: http://jsfiddle.net/8DHfY/4/

this.$get = ['$log', '$rootScope', function($log, $rootScope) {

    _this.connection = new WebSocket(this.host);
    _this.connection.onopen = function(){
        $log.log('Websocket connected to %s', _this.host);
        $rootScope.$emit('websocket.connected');
    };
    return _this;
}];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top