2014-01-23 31 views
0

依赖我想使用监听器的依赖,但WebSocket的是undefinedAngularjs如何调用asyncron服务方法,以及如何使用监听器

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

和想调用一个服务方法(谁依赖asyncron方法)准备好时

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

谢谢。

守则的jsfiddle http://jsfiddle.net/8DHfY/3/或这里

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'); 
     }; 
    }]; 
}]); 

回答

0

提供商调用注射时的$ get函数和使用的无论是从函数返回的单。

这意味着你不会从$ get函数返回任何东西,它使用undefined。

这里有一个更新的小提琴: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; 
}]; 
相关问题