當我成功發佈到我的Pubnub頻道時,我想查看消息歷史記錄以及傳入消息。本教程下面,我創建了以下控制器(分量/聊天/ chat.controller.js)如何使用角度1從Pubnub獲取消息歷史記錄和傳入消息 - es6
/*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
,但我不知道是什麼麻煩拍攝這個