使用laravel作为后端API和AngularJS作为前端的实时通知

时间:2018-04-26 05:24:28

标签: php angularjs laravel laravel-5 notifications

当后端api是laravel时,是否可以在AngularJS中使用实时通知?我应该在AngularJS中使用laravel echo还是有其他解决方案?

正如我搜索过的那样,我应该使用pusher作为websocket服务器,并且应该使用laravel echo这是一个JS库。

问题是我应该在AngularJS中使用laravel-echo库还是有另一种解决方案?

仅供参考:laravel(后端)api与AngularJS(前端)分开,它们通过使用O-Auth进行身份验证的CRUD请求进行通信。

2 个答案:

答案 0 :(得分:2)

我已经设法使用laravel + redis + socket.io + socket客户端解决了这个问题,我把解决方案放在这里希望不要浪费别人的时间。

cd your-project-name

安装包

npm install express ioredis socket.io --save

您的package.json文件看起来像

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8",
    "laravel-elixir": "*"
  },
  "dependencies": {
    "express": "^4.12.4",
    "ioredis": "^1.4.0",
    "redis": "^0.12.1",
    "socket.io": "^1.3.5"
  }
}

composer require predis/predis

创建活动

php artisan make:event EventName

确保implements ShouldBroadcast

整个EventName.php类应如下所示:

<?php namespace App\Events;

use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class EventName extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $data;

    public function __construct()
    {
        $this->data = array(
            'power'=> '10'
        );
    }

    public function broadcastOn()
    {
        return ['test-channel'];
    }
}

在角度js中使用此代码:

<script src="js/socket.io.js'"></script>
    <script>
        //var socket = io('http://localhost:3000');
        var socket = io('http://192.168.10.10:3000');
        socket.on("test-channel:App\\Events\\EventName", function(message){
            // increase the power everytime we load test route
            $('#power').text(parseInt($('#power').text()) + parseInt(message.data.power));
        });
    </script>

路由 设置三条路线就像这样。将它们添加到您的app/Http/routes.php文件中。

Route::get('/', function() {
    // this doesn't do anything other than to
    // tell you to go to /fire
    return "go to /fire";
});

Route::get('fire', function () {
    // this fires the event
    event(new App\Events\EventName());
    return "event fired";
});

Route::get('test', function () {
    // this checks for the event
    return view('test');
});

在项目根目录中创建socket.js文件

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel', function(err, count) {
});
redis.on('message', function(channel, message) {
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

仅供参考:确保已安装redis服务器+使用Laravel或数据库文件将其连接到.env

答案 1 :(得分:0)

我之前使用@Mohammad_Hosseini的解决方案,但是在将Laravel 5.4升级到5.8之后,它不再起作用了。 最后但并非最不重要的; @Mohammad_Hosseini的解决方案不包括身份验证和私有渠道。

因此,我强烈建议使用laravel-echo-server进行轻松升级。而且,它是伟大社区的开源和维护。