【问题标题】:angularjs, sockjs, angular-sockjs injection not workingangularjs,sockjs,angular-sockjs 注入不起作用
【发布时间】:2014-07-10 18:54:40
【问题描述】:

我正在尝试将 Angular 与 sockjs-client 和 cyclone 一起使用,存在一个由 bentrucker 制作的组件:https://github.com/bendrucker/angular-sockjs。所有这些技术的新手,当我尝试使用来自 bentrucker 的组件时,我遇到了注入问题。我进行了检查,该组件作为依赖项包含在 Angular 应用程序的主模块中。我正在使用 angular 1.2.19,angular-route 1.2.19 错误跟踪是:

Error: [$injector:unpr] http://errors.angularjs.org/1.2.19/$injector/unpr?p0=%24socketsProvider%20%3C-%20%24sockets
v/<@http://localhost:8888/vendor/angular.min.js:6
dc/l.$injector<@http://localhost:8888/vendor/angular.min.js:36
c@http://localhost:8888/vendor/angular.min.js:34
dc/n.$injector<@http://localhost:8888/vendor/angular.min.js:36
c@http://localhost:8888/vendor/angular.min.js:34
d@http://localhost:8888/vendor/angular.min.js:35
dc/g/<.instantiate@http://localhost:8888/vendor/angular.min.js:35
Pd/this.$get</<@http://localhost:8888/vendor/angular.min.js:67
z/<.link@http://localhost:8888/vendor/angular-route.min.js:7
K@http://localhost:8888/vendor/angular.min.js:54
f@http://localhost:8888/vendor/angular.min.js:47
fc/this.$get</z/<@http://localhost:8888/vendor/angular.min.js:46

这是我项目的结构:

app/
 client/
    scripts/
        controllers/
             main.js
        app.js
    vendor/
        sockjs-client/
           sockjs-0.3.min.js
        angular.min.js
        angular-route.min.js
        json3.js
        socket.js //this is the component from bendrucker
    views/
    ...
    index.html
 server/
    server.py

这里是 index.html

<!doctype html>
<html class="no-js">
  <head>
     <meta charset="utf-8">
     <title>Kertin 4 WEB </title>
     <meta name="description" content="">
     <meta name="viewport" content="width=device-width">
     <link rel="stylesheet" href="styles/bootstrap.min.css">
     <link rel="stylesheet" href="styles/main.css">
  </head>
  <body ng-app="KertinWeb">
    <div class="header">
       <ul class="nav nav-pills pull-right">
         <li class="active"><a href="#index">Home</a></li>
         <li><a href="#contactenos">About</a></li>
         <li><a href="#buscador">Contact</a></li>
       </ul>
       <h3 class="text-muted">KERTIN 4 WEB</h3>
    </div>
    <div ng-view></div>
    <script src="vendor/angular.min.js"></script>
    <script src="vendor/angular-route.min.js"></script>
    <script src="vendor/sockjs-client/sockjs-0.3.min.js"></script>
    <script src="vendor/socket.js"></script>
    <script src="scripts/app.js"></script>
    <script src="scripts/controllers/main.js"></script>
  </body>
</html>

脚本/app.js:

function KertinRouteConfig($routeProvider) {
    $routeProvider.
        when('/index', {
            controller: ReceptorController,
            templateUrl: '../views/receptor.html'
        }).

        when('/contactenos', {
            controller: ContactenosController,
            templateUrl: '../views/contactos.html'
        }).
        when('/buscador', {
            controller: BuscadorController,
            templateUrl: '../views/buscador.html'
        }).
        otherwise({
            redirectTo: '/index'

        });
}

var kertinServices = angular.module('KertinWeb', ['ngRoute','bd.sockjs']);

kertinServices.config(KertinRouteConfig);

kertinServices.factory('sockets', function(socketFactory){
    return socketFactory;
});

脚本/控制器/main.js:

function ReceptorController($scope, $sockets){ //this is the one with the problem
    $sockets.open("http://ip_address:8888/query");
    $sockets.setHandler('message', function(msg){
        $scope.state = msg;
    })
}
function ContactenosController($scope){

}
function BuscadorController($scope){

}

路由器机制正常工作,所有视图现在几乎都是空的。当我收到错误时正在加载索引。我正在使用的服务器以防万一:

import sys
import os
import time

import sockjs.cyclone

from cyclone.web import RequestHandler, Application, StaticFileHandler

from twisted.internet.task import LoopingCall
from twisted.internet import reactor
from twisted.python import log

settings = {
    "static_path": os.path.join(os.path.dirname(os.path.dirname(__file__)), "client")
}



class IndexHandler(RequestHandler):
    """ Serve the chat html page """
    def get(self):
        self.render('../client/index.html')


class QueryConnection(sockjs.cyclone.SockJSConnection):

    participants = set()

    def __init__(self, session):
        sockjs.cyclone.SockJSConnection.__init__(self, session)
        lc = LoopingCall(self.newMessage)
        lc.start(1)

    def newMessage(self):
        self.broadcast(self.participants, str(time.time()))

    def connectionMade(self, info):
        self.broadcast(self.participants, "Someone joined.")
        self.participants.add(self)

    def messageReceived(self, message):
        self.broadcast(self.participants, message)

    def connectionLost(self):
        self.participants.remove(self)
        self.broadcast(self.participants, "Someone left.")

if __name__ == "__main__":
    def main():

        QueryRouter = sockjs.cyclone.SockJSRouter(QueryConnection, '/query')

        app = Application([
                        (r"/", IndexHandler),
                        (r"/(.*)", StaticFileHandler, dict(path=settings['static_path'])),
        ] + QueryRouter.urls, **settings)
        reactor.listenTCP(8888, app)
        reactor.run()

    log.startLogging(sys.stdout)
    main()

【问题讨论】:

    标签: javascript angularjs python-2.7 websocket sockjs


    【解决方案1】:

    原来问题是只有 Angular 上的核心服务应该以'$'为前缀,自定义模块不应该有'$'所以在 controllers.js 上的正确方法是:

    function ReceptorController($scope, sockets){
        var conn = sockets({'url':'http://ip_address:8888/query'});
        conn.setHandler('message', function(msg){
            $scope.state = msg;
        })
    }
    function ContactenosController($scope){
    
    }
    function BuscadorController($scope){
    
    }
    

    更多:http://henriquat.re/basics-of-angular/services-dependency-injection/services-and-dependency-injection-in-angularjs.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2017-01-28
      • 2018-05-17
      • 2012-11-23
      相关资源
      最近更新 更多