Can I call a $modal.open after node server is stopped - javascript

I am new to the Angular and Node javascript development.
My question is if i stop the Node server I want to show a warning message to the user and direct the user to the login screen, so can i call $modal.open to show a modal view page and on user confirmation redirect the user to login screen and close out the session. My apologies if this is a stupid question.
Thank you.

Once an Angular page has been loaded in the browser, the node server is irrelevant unless you start making Ajax calls -- the clientside angular code will happily keep on running clientside for as long as the user keeps the browser window open.
If your goal is to detect that the server has stopped responding to XHR requests (for whatever reason) and show a modal in response, you can certainly do that -- the following config block for example would globally catch any server error and let you Do Stuff as needed:
.config(function ($httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (err) {
// Do Stuff Here.
// (More realistically you'd want to inspect the contents of the
// 'err' variable to determine what type of error you're
// dealing with, and decide which Stuff to Do based on that)
return $q.reject(err); // pass the rejection on to any downstream promise handlers
}
};
});
});
(More detail here: https://docs.angularjs.org/api/ng/service/$http )
Whether you can use that to redirect to a login screen and let the user clear their session depends on how you're serving out that login screen, and how you're clearing out sessions -- if all of those are purely clientside operations in your setup, it'll work fine; if any depend on the server which you've stopped, then presumably it won't work fine.

Related

Angular and Server Sent Events: close method call does not close the data stream

Tech stack: Angular 7, Spring webflux (with spring boot), Chrome browser
I cannot share the actual code due to policy restrictions. Appreciate your understanding.
I have followed this example: https://medium.com/#chrisbautistaaa/server-sent-events-in-angular-node-908830cc29aa
I have a boolean variable makeCall acting as a condition switch for my if else
When user clicks a button on screen toggleSseCall method containing the below logic is called in Angular component
Body of toggleSseCall method:
makeCall: boolean = true;
toggleSseCall() {
let eventSource = new EventSource(url);
if(makeCall) {
Call service method: getServerSentEvents(eventSource) //similar to the example in link one difference being i'm passing the Instantiated eventSource reference
Subscribe to the observable returned by the above call like in the example and console log the data
} else { //When user clicks the button again, call goes here as makeCall is false
//Call flow comes here as expected, I verified that with console logging
eventSource.close(); //I verified to make sure the close method is not uppercase or anything like that
}
makeCall = !makeCall //toggle boolean flag
}
Server side:
Just RESTFul Get Api call that returns Flux and the Flux just returns hello string every x seconds
The call is happening and the "hello" text streams from back-end to front-end as expected. But, the data stream doesn’t stop on call to close method. I want the data stream to close when user clicks the button again. Would appreciate any suggestions on this.
A bit late, but I just came across this issue myself. For me, this only happens when developing locally via ng serve, using the Webpack dev server to proxy requests to my backend app.
The proxy is implemented using the NPM package http-proxy-middleware. There's
an unresolved issue suggesting this is a bug.
When the browser connects directly to the backend API, this issue doesn't happen for me.

How to run function in background with service worker

I am building a javascript Web Application. In there i want to upload pictures and other data to a server. This is all working, but i want to use the application offline as well. Therefore i implemented the indexedDB, to store the data offline. Furthermore i made a sync-function, which will be executed every 5 seconds (setIntervall()...) to syncronise the data to the server if there is a internet connection again.
The problem is, that this sync-function only works when the app is open. So I researched a method to solve my problem and i got the idea of a "service worker" with background sync.
The problem is i don't know how to implement it.
This is what i currently have (the whole app is programmed in MVC-concept):
I have a sw.js with the following code:
if (event.tag == 'myFirstSync') {
event.waitUntil(sync());
}
});
In the controller there is the function sync() for synchronising the data
You can implement your background sync inside of your sw.js file, in the handler for the 'sync' event:
self.addEventListener('sync', function(event) {
if (event.tag == 'myFirstSync') {
event.waitUntil(() => {
// Put your sync code here.
});
}
});
At some point after you register your service worker, you need to trigger a sync:
// Register your service worker:
navigator.serviceWorker.register('/sw.js');
// Then later, request a one-off sync:
navigator.serviceWorker.ready.then(function(swRegistration) {
return swRegistration.sync.register('myFirstSync');
});
After triggering the sync once, if it fails, the sync should keep on retrying on its own (even if the app is not open in the browser).
If it fails, another sync will be scheduled to retry. Retry syncs also
wait for connectivity, and employ an exponential back-off.
See https://developers.google.com/web/updates/2015/12/background-sync for further details.

Quickbase usertoken to supersede current user credentials/permissions

I have a custom button which is to query and possibly update an Administration App in Quickbase, which the current user doesn't require access to.
I have JS code which is executed on a button click by the user to check the admin app, etc...
my API call to check the app has the appropriate apptoken and usertoken. However, the browser still has the current user's session cached, so the API call errors out with an access denied error message.
I'm looking for either a way to make a hidden incognito window, to then execute this code, or a way to problematically force the usertoken to supersede the current user access/permissions.
I've seen where chrome extensions can use chrome.windows.create... but I have no experience with extensions, and Ideally, I don't want to have to have an extension for just this functionality, and have to possibly install it on every user's PC for this to work...
Here is a snippet of my current code... This code does work if someone has permissions to the Administration App... but this code is residing in a different application:
PreProcURL = "https://<domain>.quickbase.com/db/<dbid>?a=API_DoQuery&apptoken=<>&usertoken=<>&query={'3'.EX.'1'}";
PreProcQuery.open('GET', PreProcURL, 'async');
PreProcQuery.send();
PreProcQuery.onload = function(){
console.log(PreProcQuery.responseXML);
RunBit = (PreProcQuery.responseXML.documentElement.getElementsByTagName("runbit"))[0].innerHTML;
SupportData = (PreProcQuery.responseXML.documentElement.getElementsByTagName("supportdata"))[0].innerHTML;
if(RunBit != "1"){
$.get("https://<domain>.quickbase.com/db/<dbid>?a=API_EditRecord&rid=1&_fid_6=1&_fid_7="+rid+"&apptoken=<>&usertoken=<>");
}else{
if(SupportData == rid){
alert("This PreProc File is already in progress... please wait.");
}else{
alert("Another PreProc is already in progress... please wait.");
}
}
};
Thanks in advance for any assistance on this.
API calls executed in JavaScript that is hosted within quickbase.com (button, pages, etc.) will run as that logged in user that triggered the script. The usertoken gets ignored.
The most common way to accomplish what you are after is to write the API_DoQuery code on a server side location and then trigger it from your JS code.

http request handling in multiple html pages app cordova

I've a MPA(Multiple page application). published for Android and iOS. It simply changes the page when user want to navigate to other page(view). All things are working fine. I want to implement some backend sync features. Problem is, I make Ajax request silently in background and user can change page anytime so app can lose reference of Ajax call which is highly important for keeping track of synced data.
Is there any plugin that can make http request on native code level or some other work around.
Have a look at cordova-plugin-http, it is a native plugin that executes all HTTP requests on a background thread.
Installation:
cordova plugin add cordova-plugin-http
Example POST request:
cordovaHTTP.post("https://google.com/", {
id: 12,
message: "test"
}, { Authorization: "OAuth2: token" }, function(response) {
// prints 200
console.log(response.status);
try {
response.data = JSON.parse(response.data);
// prints test
console.log(response.data.message);
} catch(e) {
console.error("JSON parsing error");
}
}, function(response) {
// prints 403
console.log(response.status);
//prints Permission denied
console.log(response.error);
});
There is no OOB way to do this. You can use something like the Cordova HTTP plugin to move HTTP requests to the native side, which will continue to execute across multiple pages, but it won't know what to do with the response once the response comes back if the user navigated to another page.
If your processing really is all background and doesn't truly need any JavaScript post-processing, you could try to look into something like the cordova-plugin-background-download - that basically executes a GET request in the background and saves the result where you tell it. It only supports GET, but it can work even if your whole app is put into the background.
If you need post-processing or non-GET requests, you can consider implementing your logic in native code in a plugin (perhaps using one of the HTTP plugins for Cordova to help with the actual network marshalling).
It'd be awesome if Cordova could support something like service workers, and I've been looking into that here and there. There's an old implementation for iOS but it doesn't seem to work anymore (and may not really be workable without extensive changes): cordova-plugin-serviceworker.
One other option would be to make your app a pseudo-SPA with some iframes. Have an iframe doing your requests and processing, and create interaction between the content iframe as needed. But that isn't trivial either.

Ember js run function when user closes window

I have an ember application where users are stored in a MySQL database. When a user exits (ie. closes their browser window), they need to be deleted from the database. I have the following code in one of my route files:
setupController: function () {
$(window).on('beforeunload', () => {
this.get('currentUser').delete();
});
},
In my testing this only seems to delete the user from the database maybe 70-80% of the time, and somehow it seems to be random whether it works or not. I'm guessing this is because sometimes the function isn't run in time before the browser has closed the window. How can I ensure the code to delete a user is executed every time a user exits?
It wouldn't work this way. Reason: browser interrupts any requests (even ajax) to backend when user closes window/tab.
I suggest to implement cleanup on backend side. What you need is store last time when user performed some action and delete those who did not make any requests in some period of time (for example, if there was no requests in 1 hour, you can be pretty sure that user closed browser window). You can also perform "ping" requests from your ember app to your backend once in a while, so idle users will not be deleted.

Categories