2014-01-23 70 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; 
}]; 
相關問題