gpt4 book ai didi

javascript - Laravel Echo - 无法加入状态 channel

转载 作者:行者123 更新时间:2023-11-28 03:19:08 25 4
gpt4 key购买 nike

我正在尝试使用 Javascript 库 Echo 加入状态 channel 。我可以成功加入常规 channel 。

所以,这就是我所做的:

我像这样触发事件:

 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);
}
}

监听方法很简单,我只使用如下的handle方法:

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 相同的 channel 名称部分 - channel 名称是正确输出):

$(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的存在 channel ,但没有成功。没有显示错误。我该如何调试这个?

包调试器(laravel-websockets)显示事件已触发,但没有看到连接:

This is when I get to the page (where the Echo code is supposedly called).

Event is callled

最佳答案

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

关于javascript - Laravel Echo - 无法加入状态 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59344886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com