“未捕获的类型错误:无法在 Websocket Angular JS 上读取未定义的属性‘延迟’”
Posted
技术标签:
【中文标题】“未捕获的类型错误:无法在 Websocket Angular JS 上读取未定义的属性‘延迟’”【英文标题】:"Uncaught TypeError: Cannot read property 'defer' of undefined at Websocket Angular JS" 【发布时间】:2017-09-24 23:45:11 【问题描述】:我对网络技术很陌生,我从互联网上获得了一些代码片段,并以某种方式设法形成了这段代码。
我必须通过 API 从 websocket 将数据获取到用 angularjs 开发的 web 应用程序。
这里是代码,
angular.module("MyApp")
.service("myService", function ($rootScope, $q)
return
_prevTransmittingStatus: null,
transmitting: false,
_transmissionStatus: function () ,
socket: null,
socket_msg_id: 0,
socket_history: ,
url: "ws://localhost:4848/app/",
setOnTransmissionStatus: function (callback)
var self = this;
this._transmissionStatus = function ()
if (self.transmitting != self._prevTransmittingStatus)
self._prevTransmittingStatus = self.transmitting
callback(self.transmitting)
else
,
connect: function (callback)
var deferred = $q.defer();
var promise = deferred.promise;
var self = this
this.transmitting = true;
this._transmissionStatus();
this.socket = new WebSocket(this.url);
this.socket.addEventListener('open', function (e)
self.transmitting = false;
self._transmissionStatus();
deferred.resolve("connected")
);
this.socket.addEventListener('message', function (e)
var asJson = angular.fromJson(e.data)
var replyId = asJson.id;
var histItem = self.socket_history[replyId]
self.transmitting = false;
self._transmissionStatus();
if (angular.isUndefined(asJson.error))
$rootScope.$apply(histItem.defer.resolve(asJson.result))
else
**GetActiveDoc();/*how to call this */**
console.log("---rejected-----");
$rootScope.$apply(histItem.defer.reject(asJson.error))
);
return promise;
,
disconnect: function ()
this.socket.close();
this.transmitting = false;
this._transmissionStatus();
return this;
,
send: function (msg, scope, callback, onerror)
console.info("SEND:", msg)
var _this = this;
this.transmitting = true;
this._transmissionStatus();
if (!this.socket)
return this.connect().then(
function (histItem)
console.log("CONNECT SUCCESS", histItem)
,
function (histItem)
console.log("CONNECT ERROR", histItem)
).then(function ()
return _this.send(msg, scope);
)
else if (this.socket)
console.log("socket is open")
var deferred = $q.defer();
var promise = deferred.promise;
msg.id = this.socket_msg_id;
this.socket_history[msg.id] =
id: msg.id,
defer: deferred,
scope: scope,
msg: msg
;
this.socket_msg_id++
this.socket.send(angular.toJson(msg))
return promise
,
isConnected: function ()
return this.socket ? true : false;
);
我收到错误"Uncaught TypeError: Cannot read property 'defer' of undefined at Websocket"
只是在我第一次打开我的网络应用程序时。
谁能解释一下如何解决这个问题。
【问题讨论】:
【参考方案1】:自己解决了,只是添加/修改代码如下,
if(replyId >= 0)
$rootScope.$apply(histItem.defer.resolve(asJson.result))
【讨论】:
以上是关于“未捕获的类型错误:无法在 Websocket Angular JS 上读取未定义的属性‘延迟’”的主要内容,如果未能解决你的问题,请参考以下文章