【问题标题】:Laravel Echo - can't join presence channelLaravel Echo - 无法加入在线状态频道
【发布时间】:2019-12-15 14:34:27
【问题描述】:

我正在尝试使用 Javascript 的库 Echo 加入 Presence 频道。我可以成功加入普通频道了。

所以,这就是我所做的:

我这样触发事件:

 event(new FixtureChatroomEvent($userId, $message, $username, $profileImg, $fixtureId));

或者像这样

broadcast(new FixtureChatroomEvent($userId, $message, $username, $profileImg, $fixtureId))->toOthers();

事件看起来是这样的(看起来很丑,我知道,我稍后会通过一个类):

class FixtureChatroomEvent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $message;
    public $username;
    public $profileImg;
    public $userId;
    public $fixtureId;

    public function __construct($userId, $message, $username, $profileImg, $fixtureId)
    {
        $this->message = $message;
        $this->username = $username;
        $this->profileImg = $profileImg;
        $this->userId = $userId;
        $this->fixtureId = $fixtureId;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('fixture-channel.' . $this->fixtureId);
    }
}

监听器方法很简单,我只使用了句柄方法,看起来像这样:

public function handle(FixtureChatroomEvent $event)
{
    return $event;
}

它也是这样在EventServiceProvider注册的:

    'App\Events\FixtureChatroomEvent' => [
        'App\Listeners\FixtureChatroomEventListener'
    ],

channels.php(路由)如下所示:

Broadcast::channel('fixture-channel.{fixtureId}', function ($user, $message, $username, $profileImg, $userId, $fixtureId) {
    return [
        'message' => $message, 
        'username' => $username, 
        'profileImg' => $profileImg, 
        'userId' => $userId, 
        'fixtureId' => $fixtureId
    ];
});

BroadcastServiceProvider 看起来像这样:

public function boot()
{
    Broadcast::routes(['middleware' => ['auth:api']]);

    require base_path('routes/channels.php');
}

现在前端:我只是尝试做这样的事情(我将灯具 ID 传递给与事件 fixtureId 相同的频道名称部分 - 频道名称正确输出):

$(document).ready(function(){
    var fixtureChannel =`fixture-channel.${$('#fixture_id').text()}`;
    //var fixtureChannel = 'fixture-channel';
    console.log(fixtureChannel);
    Echo.join(fixtureChannel)
        .listen('FixtureChatroomEvent', (e) => {
            alert('ok');
            console.log('ok');
        })
        .here((users) => {
            console.log('123');
        })
        .joining((user) => {
            console.log(user.name);
        })
        .leaving((user) => {
            console.log(user.name);
        })    
    ;
}); 

现在事件被触发,但在另一边什么也看不到。我还尝试加入没有fixtureId 的出席频道,但没有成功。没有显示错误。我该如何调试呢?

软件包调试器 (laravel-websockets) 显示事件已触发,但未看到任何连接:

【问题讨论】:

    标签: javascript php laravel laravel-echo


    【解决方案1】:

    问题出在Broadcast::routes(['middleware' => ['auth:api']]); 行。我删除了中间件,如下所示:Broadcast::routes(); 我在发布此问题之前尝试过此操作,但服务器第一次返回 500 错误。只需再次刷新页面即可。

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 1970-01-01
      • 2017-05-12
      • 2018-01-24
      • 2020-04-26
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多