【问题标题】:Cannot access PrivateChannel无法访问 PrivateChannel
【发布时间】:2019-12-16 14:00:52
【问题描述】:

我第一次尝试在 Laravel 和 VueJS 上实现私有频道。我已经达到了事件按预期触发的地步,但是我无法在我想要的组件中收听它。

我遵循了安装适当依赖项的所有步骤。有人可以告诉我为什么会这样吗?

我的听众:

Echo.private('message')
                .listen('NewTeam', (e) => {
                    console.log('made it');
                });

我的活动:

namespace App\Events;

use App\Team;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

use Illuminate\Support\Facades\Log;


class NewTeam implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public $team;

    public function __construct(Team $team)
    {
        $this->team = $team;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('message');
    }

    public function broadcastWith()
    {
        return ["message" => 'A new team has arrived'];
    }

我的频道.php:

Broadcast::channel('message', function ($user) {
    return true;
});

我的推送者帐户告诉我它正在发送。但是,当我触发事件时,我没有收到来自侦听器的任何信息。

【问题讨论】:

    标签: php laravel vue.js pusher


    【解决方案1】:

    它可能是您正在使用的事件名称。在您的侦听器中,您正在侦听message 频道上的"NewTeam" 事件。

    Echo.private('message')
            .listen('NewTeam', (e) => { // <---
                console.log('made it');
            });
    

    但在您的事件中,您没有指定自定义事件名称。根据文档:

    广播名称

    默认情况下,Laravel 将使用事件的类广播事件 名称。但是,您可以通过定义一个 事件上的 broadcastAs 方法:

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'server.created';
    }
    

    所以这意味着在您的案例中使用的事件名称可能是App\\Events\\NewTeam。为了以您想要的方式解决/自定义此问题,您需要添加到您的事件类:

    app/Events/NewTeam.php

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'NewTeam';
    }
    

    【讨论】:

    • 您好@HCK,我尝试了您建议的解决方案,但似乎不起作用。有什么方法可以让我知道我的组件是否正在收听该频道?
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 2015-07-09
    • 2021-01-04
    • 2016-04-05
    • 2014-12-25
    • 2020-08-06
    • 2021-12-01
    • 2021-10-06
    相关资源
    最近更新 更多