我使用laravel 5.3
我像这样制作routes / channels.php:
<?php
Broadcast::channel('messages', function() {
return true;
});
如果我输入数据购物车并点击提交,它将运行:
this.$http.post(window.BaseUrl + '/guest/add-notification', {cart_data: JSON.stringify(data)});
它将调用控制器上的函数
这样的功能:
public function addNotification(Request $request){
$input = $request->only('cart_data');
$data = json_decode($input['cart_data'], true);
event(new CartNotificationEvent($data));
}
然后它将调用事件
这样的事件:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CartNotificationEvent
{
use InteractsWithSockets, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function broadcastWith()
{
return [
'message' => $this->data,
];
}
public function broadcastAs()
{
return 'newMessage';
}
public function broadcastOn()
{
return new Channel('messages');
}
}
在客户端,我喜欢这样:
Echo.channel('messages')
.listen('.newMessage', (message) => {
console.log('test')
console.log(message);
});
执行所有代码后,我检查控制台,console.log不显示
为什么不起作用?
如果我看到我制作的整个代码,那么过程似乎是正确的
答案 0 :(得分:1)
class CartNotificationEvent implements ShouldBroadcast
缺失。