0

I want to know if there is an equivalent of ajaxStart or ajaxStop in Angular 2.

I want to check if there's an ajax which runs into the document.

According the official documentation of ajaxStart, it will be triggered when there is any Ajax Request. And I want something like this in Angular 2.

$( document ).ajaxStart(function() {
  $( "#loading" ).show();
});

I do this:

  • into my app.component.ts, I show my loader
  • when my ajax is success, I hide my loader

But, some of my page doesn't have ajax call, so if I show my loader using my app.component.ts, it will be impossible to hide this, because, none of ajax request is present into this page.

I think, if I listen if ajax is not present into my page, if will hide my loader.

I use localStorage to save the status of ajax. If the page has ajax, I set a value to that xhr Otherwise, I remove the status stored into localStorage. Each time, the user arrive in the page. My script check, if there is an ajax running into that page.

app.component.ts

if(localStorage.getITem("xhr")) {
    // action here
}

request.service.ts

...
let checkForAjax: any = {
    setXhr () {
        localStorage.setItem("xhr", "1");
    },
    removeXhr () {
        localStorage.removeItem("xhr");
    }
}
...

into get request, I do this (before success callback):

checkForAjax.setXhr()

And into callback of get request, I just remove the status.

checkForAjax.removeXhr()

By the way, I haven't the xhr status, after my ajax is successed. So If I check it into my app.component.ts, I just test if there's a property xhrinto my localStorage.

I work now, but I want another way to listen for ajax with angular 2.

Is that way exist? How can it will be done?

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
  • check the interceptor in angular js, i think that will solve your problem. you can refer this http://codereview.stackexchange.com/questions/143194/progress-bar-loader-with-angularjs – atul Oct 19 '16 at 07:47
  • It is angular 1. Is the principe the same? In this link, there'sn't solution. – Radonirina Maminiaina Oct 19 '16 at 09:07

1 Answers1

1

You could make use of Promises

https://stackoverflow.com/a/30008115/3152269 explains it better than i ever could, but it seems right up your alley

What i generally do when i shoot off an ajax request is to make a promise to run some code after it receives a response.

This makes Ajax calls easier to read and ensures the code doesn't run unless you want it to.

Community
  • 1
  • 1
WebKenth
  • 126
  • 1
  • 1
  • 9