首页 > 解决方案 > laravel 和 react 推送器设置

问题描述

我正在做一个网络项目。

我有 laravel 作为我的后端 reactjs 作为我的前端

我有用户,在我的数据库中发表评论。

我想实现推送器,这样一旦任何用户发布了新帖子,我就可以显示这些实时帖子。

我非常接近实现这种行为。

在 laravel 上

我有这个活动

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

    public $post;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($post)
    {
        $this->post = $post;
    }

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

} 

一旦将帖子存储到我的数据库中,我就会触发此事件

event(new NewPostsCast($output)); 

在反应

let channel = pusher.subscribe("posts");
// i guess error is here because this function never called
// it's only called at startup
channel.bind("NewPostsCast", post => {
    console.log("pusher::: ", post);
});

可能有用

来自推送日志

Pusher:App\Events\NewPostsCast 的帖子没有回调

然而 pusher 也返回这个日志

Pusher : Event recd : {"event":"App\\Events\\NewPostsCast","channel":"posts","data":{"post":{"id":19,"title":"sd","body":"eksdl","tags":"[\"ds\",\"dsf\"]","user_id":1,"created_at":"2019-04-18 14:22:00","updated_at":"2019-04-18 14:22:00","votes":0,"user":{"id":1,"name":"user1","username":"user1","email":"user1@health.io","address":null,"state":null,"country":null,"gender":"female","phone":null,"avatar":"http://healthqo.api/public/profile_pics/default/female.png","created_at":"2019-04-09 08:30:12","updated_at":"2019-04-09 08:30:12"}}}}

标签: phpreactjslaravelpusher

解决方案


以防有人仍在为同样的问题而苦苦挣扎

从推送日志中显示(App\Events\NewPostsCast 的帖子没有回调),这完全解决了问题

因为 react 和 laravel 在我的项目(NewPostsCast)中是分开的,所以我不得不改变绑定函数的第一个参数

像这样:

let channel = pusher.subscribe("posts");
channel.bind("NewPostsCast", post => {
    console.log("pusher::: ", post);
});

let channel = pusher.subscribe("posts");
channel.bind("App\\Events\\NewPostsCast", post => {
    console.log("pusher::: ", post);
});

不知道为什么双双反斜杠,但它给了我一个单反斜杠的语法错误


推荐阅读