我正在为新消息构建通知,并希望立即将这些通知广播到客户端。我的代码可以广播新消息通知,但问题是监听数据和刷新消息列表。
发送通知代码
class NewMessage extends Notification implements ShouldQueue
{
use Queueable;
private Message $message;
private User $sender;
public function __construct($mes)
{
$this->message=$mes;
$this->sender=User::find($mes->from_id);
}
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return['database','broadcast'];
// return ['mail', 'database','broadcast'];
}
/**
* Get the mail representation of the notification.
*/
public function toMail(object $notifiable): MailMessage
{
$url = url('/moncompte/mesmessages/'.$this->message->from_id);
return (new MailMessage)
->subject('New Message')
->line('You have receiveid a new message.')
->action('View Message', $url)
->line($this->message->body);
}
/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toDatabase(object $notifiable): array
{
return [
'id' => $this->message->id,
'from_id' => $this->sender->id,
'name' => $this->sender->name,
'content' => ' send you a message'
];
}
public function toBroadcast(object $notifiable): BroadcastMessage
{
return new BroadcastMessage([
'id' => $this->message->id,
'from_id' => $this->sender->id,
'name' => $this->sender->name,
'content' => ' send you a message'
]);
}
}
用于监听通知通道并调度新的监听以刷新数据的代码
window.Echo.private(`App.Models.User.${userId}`)
.notification((notification) => {
console.log(notification.type);
Livewire.dispatch('refreshData');
});
监听刷新数据的代码
#[On('echo-private:App.Models.User.{user.id}')]
public function refreshData2()
{
dd('refresh2');
$this->notifications=$this->user->notifications->where('type','!=','App\Notifications\NewMessage');
$this->messages=$this->user->notifications->where('type','==','App\Notifications\NewMessage');
}
#[On('refreshData')]
public function refreshData()
{
dd('refresh');
$this->notifications=$this->user->notifications->where('type','!=','App\Notifications\NewMessage');
$this->messages=$this->user->notifications->where('type','==','App\Notifications\NewMessage');
}
但是它不起作用,并且在控制台中出现该错误
Uncaught TypeError: Cannot read properties of undefined (reading 'charAt')
at e.value (app-c7bad5b3.js:5:10126)
at n.value (app-c7bad5b3.js:5:10732)
at livewire.js?id=8a199ab2:8657:46
at Array.forEach (<anonymous>)
at Array.<anonymous> (livewire.js?id=8a199ab2:8634:16)
at trigger (livewire.js?id=8a199ab2:433:34)
at Component.processEffects (livewire.js?id=8a199ab2:4371:7)
at new Component (livewire.js?id=8a199ab2:4340:12)
at initComponent (livewire.js?id=8a199ab2:4400:21)
at livewire.js?id=8a199ab2:8267:26
对于遇到同样问题的人,解决方案是这里。这节省了一整天的时间。