Home > database >  How to push notification on user open component or leave it in Angular?
How to push notification on user open component or leave it in Angular?

Time:09-30

We create a report about the current opened products. We use Angular Component that is responsible to show a product by its id. So if a product page is opened, the frontend instantly sends a notification with tenantId and productId so we increase this productId in this tenantId by one and vice versa when the user closes the product component, the frontend sends a notification with tenantId and productId so we decrease this productId in this tenantId.

Scenario:-
User1 open product page so front send {"tenantId":"abc","productId":1} so in backend in temporary map increase this productId in this tenantId

User2 open product page so front send {"tenantId":"abc","productId":1} so in backend in temporary map increase this productId in this tenantId

User2 closed product page so front send {"tenantId":"abc","productId":1} so in backend in temporary map decrease this productId in this tenantId

But the problem is when the frontend sends a notification when the user closes the browser or closes the browser tap the request is already triggered but not complete.
So what is the best practice to complete this task?

No necessary this implementation you can give any workaround.

CodePudding user response:

In order to send something to the server at the moment of 'unloading' the browser tab, there is fairly well supported Native Browser API called sendBeacon (https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon). This really is unrelated to Angular and you cannot use the HttpClient for it.

it would look something like this:

document.addEventListener('visibilitychange', function logData() {
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/log', analyticsData);
  }
});

The sendBeacon is almost guaranteed to be send to the server. There is no response needed from the server as the API doesn't actually expect a response to its call. Also, if you need to sent a JSON payload, you can do that using a blob like:

const payload = {'tenantId':'abc','productId':1};
const json = new Blob([JSON.stringify(payload)], { type: 'application/json' });
navigator.sendBeacon(url, json);
  • Related