Tracking all server side actions on Angular Js UI - javascript

I need to show all server side REST actions on angular js UI in my application.
Like when the user is created, I need to show User is created/failed immediately on the panel on GUI.
I am saving all such actions in DB table(Recent Activity).I need to fetch data from DB table and show it on UI.
One way to design it get latest data from DB table(Recent Activity) on every action on the UI but for that, I need to make REST call on each action which is not very maintainable code.
What is the best way to design/implement above problem in angular js?
P.S. Application backend is implemented in Springboot

When you will create a user, you are going to hit a create User API and that API will return HTTP response.
So you can check if you get a success, just notify user a success message else failure message.
Hope this helps!

Related

Get ajax call progress status in front end

I have a web page which allows users to upload and process specific files. After an user uploads some files, after clicking the 'Process' button an ajax call is being sent to a backend service. In the beforeSend function there is an overlay applied to the screen and a spinner is displayed. When the success function is triggered, then the overlay is removed and a toast notification is being shown like 'Files were processed!'
My goal is to somehow show a progress status for each file based on specific checkpoints in the backend service.
Let's say that the backend service when called does following tasks: parse file, map to specific format, send data to database A.... and in the end it sends back http status 200 and a JSON like
{
"status":"Success",
"message": "File X was processed"
}
Now what I want is that instead of just getting an overlay and disabling the whole page until the success event is triggered, to have a progress bar which is updated for each file based on the exact step where the backend has reached.
For instance, for file A, I would like to see below transitions: 5 % Parsing file, 10 % Mapping file...90% sending data to database, 100% processed.
Is this somehow achievable?
There are few points that you need to look into.
Usually in production code, we need to have timeouts. If you are making an ajax call to the backend API, there will be a timeout associated with that api call. Suppose if the timeout is more than 2 mins, then it will send you a 504 Gateway timeout error.
To overcome this and to implement the functionality which you want, you can have any DB(lets consider SQL server). In your SQL server, make a table:
Process_Table
With schema:
Process_id( Will store the process id/name )
Percentage( Will store the percentage )
At_step ( Parsing, Mapping, Sending to DB etc)
Using Javascript(Or any framework of your choice), use setInterval(), to make check_process() api calls. For check_proceess, you can pass in the process_id, and check against the db. For interval, you can set it to 5 seconds. So that every 5 seconds the call is made.
You can read the response of those API calls and do your processing.
An HTTP request consists of a request and a response. There's no direct way to get status updates beyond the onprogress event which would let you see how much data has been transferred. This is useful for determining how much of the data has been sent to the server, but not so much for how far the server has got with working with that data.
You could store progress in a database and poll a webservice to read the most recent status.
You could also have the server push updates to the client using Websockets for bi-directional communication.
A rough outline for such a system might look like:
Open a Websocket
Send files with Ajax
Get server generated ID back in HTTP response
Pay attention to messages coming over the Websocket that mention that ID
You could also look at doing the whole thing over Websockets (i.e. upload the files that way too). A quick Google search turns up this library for uploading files to a Websocket service hosted on Node.js.

How to receive data from another server (like push notification)

When a user scans QR code in our web page and makes purchase with it (using a 3rd party application), I want to hide that QR code and process the purchase.
I got an API to check whether the transaction was successful or not. My first thought was sending a request to that API every 2 seconds to check the transaction (terrible idea?). But they told us to create something called a "hook" and they would subscribe to it. What's that? How should I implement that?
Hook may generally mean webhook, here is the wikipedia description.
Webhooks are "user-defined HTTP callbacks". They are usually triggered
by some event, such as pushing code to a repository or a comment being
posted to a blog. When that event occurs, the source site makes an
HTTP request to the URI configured for the webhook.
Hook/Webhook
Think a hook as an endpoint, where a user can notify you / giving you information.
The way it work is like a user accessing a url and sending params
your-url.com/hook?order_id=123&status=complete
Warning: Example code, generally a good hook should provide authentication method.
That way your server can interpret that information as
order with id 123 has been completed
That was a basic implementation.
Other easier analogy is:
a user accessing a url and input a form and press submit. To which url the data is sent, that url can also be called hook.
Basically they are telling you to implement a service that they would call when a transaction ocurred successfully, instead of you going to them.

Should I use an API for this simple event (Express JS)

I havebeen having trouble with backend for a while now and Express JS has made it especially hard. However, I think I am to blame, because I've been going at with the approach that it was an MVC framework generator or maybe it was a framework that helps with authentication. But if I am correct, Express JS should reflect a RESTful API for everything. Not just for user sign up (POST) and loggin in (GET).
This is where I am kinda need clarification. From now on, is it best practice to always use RESTful API when interacting with a database? A real issue I had was with a user table and a likes table.
If a user clicks a like button on a photo, I want to do something like:
INSERT INTO likes (user_id, photo_url) VALUES (current_user, url);
What would the approach be to do this? How do I tell the like button to refer to the API? It's not like a signup form, where we give them names. Or do I just go into the Express file and start defining routes?
Yes, you create an express route for each ajax call that you wish the client to be able to make.
Here's the general sequence of events for a Like button on a photo:
User logs in. That creates some sort of state in the cookie that identifies the user (either an ID or more likely a server-side session).
User presses Like button on a photo.
Javascript attached to the Like button in the browser, gets the current photo ID and makes an Ajax call for "likePhoto" with the current photo ID as a parameter for the Ajax call.
The Ajax call hits an Express route that you have previously set up to handle this Ajax call.
If there is no logged in user session associated with this request, then the request is probably denied (probably returns some error code associated with unauthorized).
The Express route uses the cookie to identify the user making the request so it now has the photo ID and the user so it can make the database call to add the Like to the DB.
After the DB operation completes, the ajax call can return a 200 status and whatever response is appropriate.

Angular $http get watch an api for data changes

I am using DRF and AngularJS for my website. I make a simple request like-
$http({
method: "GET",
url: "http://127.0.0.1:8000/api/sendeop",
}).then(function success(response) {
//some processing on the data returned
}, function error(response) {});
Now if data changes in the database, it is not reflected on angularJS as this only makes the request once while it loads. How to watch the api for data change and process it in angularJS?
I'm not quite sure if $watch or $digest solve my problem, but if they do, how do I use them?
From your problem statement I understand the following:
You have a backend DB. The server-side/middleware queries the DB and sends the data to the front-end.
The client/front-end which is using Angular JS is accepting the data from the server side and utilizing it in the screens.
You want to check if the data in the backend DB is changed and if it is changed you want the client to request the data and refresh the screen content.
If the above understanding is correct, then I would suggest the following:
(For capturing changes of data in a single row)
Add a tsChanged(TimeStamp for changed data) column in the table which is storing the data in the DB.
Every Update query will update the tsChanged field of the row.
When the data will be first sent to the client then the tsChanged of the that state is also sent to the client.
Create a service (say updateCheckerService) in the server side that compares the tsChanged values (between the current tsChanged in the DB vs the tsChanged that is sent from the client side). A light weight Select query will do.
Using $interval hit the updateCheckerService by passing the tsChanged thats already present in the client side.
If the server responds true (means the data is changed), then call the data load service again.
(For capturing the changes of the data in multiple rows)
Add a tsChanged column in the table which is storing the data in the DB.
Every Update query will update the tsChanged field of the row.
When the data will be first sent to the client then the highest value of tsChanged is sent to the client.
Create a service (say updateCheckerService) in the server side that compares the tsChanged values (between the current highest tsChanged in the DB vs the tsChanged that is sent from the client side). A light weight Select query will do.
Using $interval hit the updateCheckerService by passing the tsChanged thats already present in the client side.
If the server responds true (means the data is changed), then call the data load service again.
Advantages:
Since the Client side data loading service is expensive and heavy, its best to call only when you are sure that the data is changed in the DB.
In order to be sure that the data is changed, we are using a light weight service, thus effectively making the process lighter.
Hope it helps!
wel you got it all wrong, angular js is client side scripting language only,
if you want to track the changes in database and want to show updated data.
you will need to take help any of middleware (i.e socket.io) or
you can use webworkers for ajax poling which will make continous http call to your server in every definite interval or
you can use any third party (i.e. firebase or PubNub) library.
You can implement a notification system (see Amazon SQS or SNS), or, as stated by #str, you can implement a real-time call (see ajax long polling, websockets).

Get Initial Data for a Page in angular

I have created a backend using Django REST and for handling API's at frontend I am using Angular (I have just started using angular).
I have one initial page let say User Profile Page So If user is authenticated I wants to show His profile on that initial page. All Authentication related thing is handled in API's So I am just getting response and redirection to profile page or login page is handled via Django.
I can get user related data in django and render that to HTMl page but in that case Angular functions cannot serve this django data.
So what will be the best way that whenever this profile page url is loaded an API call will be made that will fetch user data and angular can show that data in template and will be able to use it further ?
EDIT
let say you open this url -> /user-profile/ which refer to below View
class HomeView(TokenRequiredMixin, TemplateView):
"""
"""
template_name = 'portal/index.html'
mixin_failed_url = reverse_lazy('login-view')
It basically render to profile apge , here in this view I can fetch the user data and show them on HTML but angular will not be serve in this case.
One way to do this call any angular function using ng-init and load user data that will server the angular issue but its not the best way to do I guess.

Categories