In real time with AngularJs & Yii2

I am developing a Yii2 REST API, with AngularJS to use the interface.

I need a way to implement a real-time approach, for example. to chat or to receive real-time notifications.

Is it possible how to achieve? I read about Ratchet, Socket.io and some other things, but I couldn't figure out how to make them suitable for REST or if this is the way to go.

Any advice would be appreciated.

+5
source share
1 answer

Here you have several options.

Short / long poll (use setTimeout)

app.controller("MyController", function($scope, $timeout, $http) { $scope.messages = []; $timeout(callAtTimeout, 3000); function callAtTimeout() { console.log("Timeout occurred"); $http.get('PATH TO RESOURCE TO GET NEW MESSAGES').then( function(res) { // update $scope.messages etc... }, function(err) { // handle error } ); } }); 

For a short and long survey on the client side, you send a request, wait for a response, then wait 3 seconds and run again.

Short / long polling works differently on the server side. Short polls will simply return the answer immediately - whether something has changed or not. Long polling, you keep the connection open and when there is a change, then you return the data. Beware of too many connections.

Socket.io (websockets)

I would recommend you implement websockets using either something like node.js on your own web server, or as a hosted solution like Firebase.

The thing with Firebase is that with PHP you can send a request to send a REST endpoint to a firebase server. Your javascript can connect to this endpoint and listen for the changes and update the dom accordingly. Perhaps this is the easiest of all.

I personally have not used PHP to program sockets, but this can be done.

0
source

All Articles