开发者问题收集

Angularjs 1.4.4:未捕获的 ReferenceError:$rootScope 未定义

2018-04-06
368

我想使用 SockJs 从服务器端接收 stomp 发布的所有事件。我已创建 WebSocketController。它在 app.js 中启动为

.controller('webSocketController', webSocketController)

WebSocketController.js

class WebSocketController {

  constructor($rootScope, $scope) {
   Object.assign(this, {$rootScope, $scope});
    this.onConnected = this.onConnected.bind(this);
    this.stompClient = '';
    let vm = this;

    setTimeout(function () {
            vm.connect();
    }, 2000);
  }

  onConnected(frame) {
    console.log('Connected: ' + frame);
    this.stompClient.subscribe('/topic/public', this.showMessage);
  }

  onError(error) {
      console.log("Could not connect to WebSocket server. Please refresh this page to try again!");
      console.log("error: ", error);
  }

  connect() {
    var socket = new SockJS('/ws');
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, this.onConnected, this.onError);
  }

  showMessage(message) {
      console.log("message received: ",message);
      $rootScope.$broadcast('refreshAccessPointList');
  }

  getStompClient() {
    return this.stompClient;
  }

}

var MyController = new WebSocketController();
MyController.$inject = ['$scope', '$rootScope'];
export default MyController;

当 showMessage() 尝试广播收到的事件时,无法找到 $rootScope。 控制台显示:Uncaught ReferenceError:$rootScope 未在 l 处定义 (webSocket.controller.js?eaab:33) 知道我遗漏了什么吗?

2个回答

在课程结束后, 将依赖项注入到控制器类 然后注入到模块

export class WebSocketController {

  constructor($rootScope, $scope) {
   Object.assign(this, {$rootScope, $scope});
    this.onConnected = this.onConnected.bind(this);
    this.stompClient = '';
    let vm = this;

   ....
   ....
   ....


  getStompClient() {
    return this.stompClient;
  }

}

现在,

将依赖项注入到控制器类:

WebSocketController.$inject = ['$rootScope', '$scope'];

将控制器依赖项注入到模块:

angular.module('app').controller('WebSocketController', WebSocketController);

Sravan
2018-04-06

您应该在创建控制器实例之前设置 $inject 注释

WebSocketController.$inject = ['$rootScope', '$scope'];
export class WebSocketController;

此外,我认为您不需要手动创建 WebSocketController 实例。

someModule.controller('WebSocketController', WebSocketController);
Martin Hlavňa
2018-04-06