laravel和react pusher设置

时间:2019-04-18 15:05:44

标签: php reactjs laravel pusher

我正在研究一个Web项目。

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

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

我想实现pusher,以便一旦有任何用户发布新帖子,我就可以显示此实时帖子。

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

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

可能有用

来自推送日志

  

推送器: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"}}}}

1 个答案:

答案 0 :(得分:0)

  

万一有人还在为同样的问题而苦苦挣扎

从pusher日志中说(在App \ Events \ NewPostsCast的帖子中没有回调) 可以解决问题

因为我的项目中没有将react和laravel分开(NewPostsCast),所以未定义 所以我不得不更改绑定函数的第一个参数

像这样:
FROM

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

不确定为什么要使用双反斜杠,但是单反斜杠会给我带来语法错误