我在ReactJS应用程序中有以下函数,它应该初始化我正在使用的Twilio服务。但是,似乎无法正确访问Twilio频道。这是我的代码:
componentDidMount() {
let chatClient = this;
$.ajax({
method: "GET",
url: 'get_twilio_token',
data: {device: chatClient.device},
success: (data) => {
let accessManager = new Twilio.AccessManager(data.token);
//let messagingClient = new Twilio.Chat.Client(data.token);
let messagingClient = new Twilio.Chat.Client.create(data.token).then(client => {
client.getUserChannelDescriptors().then(channels => {
let channelsHash = {};
console.log('inside callback of messagingClient2')
channels.items.map(channel => {
channel.on('messageAdded', () => {})
channelsHash[channel.uniqueName] = channel;
});
});
});
}
});
}
此函数会在行TypeError: channel.on is not a function
中抛出一条错误消息channel.on('messageAdded', () => {})
。
感谢任何帮助。谢谢。
答案 0 :(得分:3)
getUserChannelDescriptors()
返回ChannelDescriptors
而不是Channels
。要获得Channel
,您必须为描述符https://media.twiliocdn.com/sdk/js/chat/releases/1.0.0/docs/ChannelDescriptor.html#getChannel__anchor
getChannel
答案 1 :(得分:0)
这就是我的方法
async function getChannels() {
// Initialize the chat client
this.chatClient = new Chat(this.state.twilioToken);
await this.chatClient.initialize();
// Get channel descriptors
this.chatClient.getUserChannelDescriptors().then(paginator => {
let channels = [];
let channelsBulkFetch = [];
if (paginator.items.length) {
channels = paginator.items;
// Loop through all channels and call getChannel() for each cahnnel
for (let i = 0; i < paginator.items.length; i++) {
channelsBulkFetch.push(channels[i].getChannel());
}
// Loop through each channel detailed object and perform various operations
channels.map(channel => {
// Do whatever you want with channel object
channel.on('messageAdded', this.messageAdded);
});
}
})
}
对于具有最后消息时间戳的已排序频道
async function getSortedChannels() {
// Initialize the chat client
this.chatClient = new Chat(this.state.twilioToken);
await this.chatClient.initialize();
// Get channel descriptors
this.chatClient.getUserChannelDescriptors().then(paginator => {
let channels = [];
let sortedChannels = [];
let channelsBulkFetch = [];
if (paginator.items.length) {
channels = paginator.items;
// Loop through all channels and call getChannel() for each cahnnel
for (let i = 0; i < paginator.items.length; i++) {
channelsBulkFetch.push(channels[i].getChannel());
}
/**
* Additional part for sorting
*/
sortedChannels = channels.sort(function (a, b) {
// Turn strings into dates, and then subtract them
// If channel doesn't have any message consider the dateDreated for sorting
return new Date(b.lastMessage ? b.lastMessage.timestamp : b.dateCreated) - new Date(a.lastMessage ? a.lastMessage.timestamp : a.dateCreated);
});
// Loop through each channel detailed object and perform various operations
sortedChannels.map(channel => {
// Do whatever you want with channel object
channel.on('messageAdded', this.messageAdded);
});
}
})
}