当我成功发布到我的Pubnub频道时,我希望看到消息历史记录以及传入消息。按照教程,我创建了以下控制器(component / chat / chat.controller.js)
/*jshint esnext: true */
'use strict';
class ChatController {
constructor($scope, $rootScope, Pubnub) {
this.cardTitle = "chat window";
$scope.messages = [];
$scope.channel = 'Channel-jlinog5q8';
$scope.messageContent = '';
Pubnub.init({
"publishKey": publishKey,
"subscribeKey": subscribeKey,
});
// Subscribe to messages channel
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback'],
});
// $scope.messageEvents = Pubnub.getMessageEventNameFor($scope.channel)
Pubnub.history({
channel:$scope.channel,
callback: function(payload){
console.log(payload);
$scope.messages.unshift(payload.message);
}
})
// Send the messages over PubNub Network
$scope.sendMessage = function() {
$scope.uuid = $rootScope.userInfo.first_name +' '+$rootScope.userInfo.last_name;
// Don't send an empty message
if (!$scope.messageContent ||
$scope.messageContent === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
debugger
},
error: function (error) {
debugger
console.log('Error:', error);
}
});
// Reset the messageContent input
$scope.messageContent = '';
}
// Listenning to messages sent.
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function (ngEvent, envelope) {
$scope.$apply(function () {
debugger
// add message to the messages list
$scope.messages.unshift(envelope.message);
});
});
}
activate($rootScope, PubNub, $scope) {
}
}
ChatController.$inject = ['$scope', '$rootScope', 'Pubnub'];
export default ChatController;
我能够看到消息成功发布,但我看不到我订阅的频道中的消息。
组件/聊天/ chat.html:
<ul class="collection">
<li ng-repeat="message in messages">
<!-- <img src="{{avatarUrl(message.sender_uuid)}}" alt="{{message.sender_uuid}}"> -->
<span class="title">{{ message.sender_uuid }}</span>
<p>{{ message.date | date:"MM/dd/yyyy 'at' h:mma"}}</br> {{ message.content }}</p>
</li>
</ul>
我认为问题出在$scope.$on
,但我不知道该怎么办?
答案 0 :(得分:1)
您使用的是哪个版本的PubNub Javascript SDK?从您提供的代码段,您看起来正在使用PubNub Javascript SDK v3的API。
init函数的语法看起来不对。
如果您将PubNub AngularJS SDK与PubNub JS SDK v3一起使用,它应该是:
Pubnub.init({
publish_key: publishKey,
subscribe_key: subscribeKey
});
如果您将PubNub AngularJS SDK与PubNub JS SDK v4一起使用,它应该是:
Pubnub.init({
publishKey: publishKey,
subscribeKey: subscribeKey
});
你应该更新方法以使用PubNub Javascript SDK v4的API: https://www.pubnub.com/docs/angularjs/api-reference-sdk-v4
如果它解决了您的问题,请告诉我。 马丁