Update scope properties when server data changes without client checking server angularjs - angularjs

For this method call:
$http.get("Some api call").then(function (response) {
$scope.data=response.data;
});
Suppose the response keeps on updating from time to time and I wish to update the $scope.data property whenever the response is updating without firing the $http.get using timeout or interval methods.
I am not getting any solution for this issue. Please provide your ideas with examples.

What you are asking is called Polling.
Your HTTP request will NOT get the latest data unless you fire the request again. Unless you fire the request again, your response will not have the latest data and thus, your data object will also not get updated.
No amount of $watch will suffice. Simply because, unless you poll the server periodically, you will not get the latest data.
This is how HTTP/1.1 behaves. This is soon about to change with HTTP/2
If you do not wish to make periodic requests, then have a look at sockets. You have not mentioned your backend but a Nodejs example can be found at socket.io.

Related

How to track a service whose response is keep changing after a minute in angular JS?

I am working with angular js (1.x).
I need to display some data which is coming from backend. For that I am calling a service.
Problem is that the response keep changing periodically. But still I didnt use setTimeInterval as this may overload backend due to continuously sending request from UI. So I let user to manually refresh the page to update the data.
Is there any way in which I can auto-update the data without having to use setTimeInterval?
What is a websocket?
WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.
Src: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
AngularJs + Websockets
You can use ng-websocket for angularjs
https://github.com/wilk/ng-websocket
or
AngularJS WebSocket Service Example

Prevent same requests from being sent simultaneously when using Angular resource

I have a few components in one page.
Each of them fetches the same data from the server.
As a result, when the page loads, these components send the same request multiple times.
Is there any way to prevent this? Like caching the promise of the first request and returning that to the next coming requests (before the promise resolved)?
In order to make sure that the request is sent only once, you can keep track of the first HttpPromise you create, and on subsequent calls of the function, return that same promise.
This SO link might be what you're looking for.
When calling the $http service you can additionally supply a cache object. If you do so any additional requests will use the cached value. If the same cache is used then additional requests made before the first is resolved will not call the server but wait for the response.
$http.get(url, {cache:cacheObj})
Where cacheObj is from $cacheFactory

AngularJS/Router minimize API calls

Would it be possible to make all the API calls once when the user lands on the page from the url and store all the data as cache and then use the cache to render the state changes from Angular router?
I can see it being implemented by a service that populates the rootscope but would this method be recommended instead of calling the API multiple times?
You can use use $http and set cache to true.
Should be enough for your needs.
From documentation:
The default cache value can be set by updating the $http.defaults.cache property or the $httpProvider.defaults.cache
property.
When caching is enabled, $http stores the response from the server
using the relevant cache object. The next time the same request is
made, the response is returned from the cache without sending a
request to the server.
Take note that:
Only GET and JSONP requests are cached. The cache key is the request
URL including search parameters; headers are not considered. Cached
responses are returned asynchronously, in the same way as responses
from the server. If multiple identical requests are made using the
same cache, which is not yet populated, one request will be made to
the server and remaining requests will return the same response. A
cache-control header on the response does not affect if or how
responses are cached.

Real time with AngularJs & Yii2

I'm developing a Yii2 REST API, with AngularJS for the frontend to consume.
I need a way to implement real time approach, e.g. for a chat, or to make some real time notifications.
Is this possible, how to achieve? I been reading about Ratchet, Socket.io and some other things, but I couldn't figure out how to make them fit together for REST or if this is the way to go.
Any advice would be appreciate.
You have a few options here.
Short / Long Polling (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 both short and long polling on client side, you send request, wait to get a response back, then wait 3 seconds and fire again.
Short/Long polling works differently on the server side. Short polling will just return a response immediately - whether something has changed or not. Long polling, you hold the connection open and when there is a change, then you return the data. Beware of keeping too many connections open.
Socket.io (websockets)
I would recommend that you implement websockets using either something like node.js on your own web server or a hosted solution like Firebase.
The thing with Firebase is that from PHP, you can send a post request to a REST endpoint on the firebase server. Your javascript can connect to that endpoint and listen for changes and update the dom accordingly. It is possibly the simplest of all to implement.
I personally wouldnt use PHP for socket programming but it can be done.
To have real-time updates on your website, you can implement one of the following approaches depending on your requirement and how fast you need to update your frontend component.
Using a websocket
You can use a library like https://github.com/consik/yii2-websocket to implement it with Yii2. But this will act as a separate service from your REST API. Therefore you have to make sure that proper security practices are applied.
Running an Angular function with a timeout
You can continuously poll an endpoint of the REST API with a timeout of few milliseconds to receive updated values.
The second approach will create many requests to the API which will increase the server load. Therefore my preferred approach is using a websocket.

Preventing similar POST requests with AngularJS

I am currently building a dashboard page with multiple widgets. Those widgets retrieve their data with REST calls ($resource). A few widgets make similar calls and I don't want to DDOS our server so I am looking for a way to make a call only once and resolve all similar requests with the same response.
Since I am restricted to using POST requests only, I cannot use the cache option that $resource offers. This seems to be doing exactly what I want but only for GET requests.
I was thinking along the lines of using a http interceptor to queue similar POST requests, fire only one of them and resolving them all when the first one gets its response.
However, I cannot seem to put the pieces together so any help is appreciated. I am open to other options.
Kind regards,
Tim
Services in AngularJS are singletons, so a solution would be to store the response in the service, as a variable. Then next time you'll do the request, previously check if the variable is null, if it's not you wrap it in a promise and returned it. If it's null, then you do the request, and store the response for the next call.
You can also either use this in your request service or in your interceptor service.
I hope I helped !
Refactor your widgets to depend on a service (singleton).
This service should either poll the server via XHR, or get server push via websocket for updates.
If polling, look into server side caching and etags.

Resources