JDillon522
JDillon522

Reputation: 19666

Angular 2 - Cancel pending GET request in HttpInterceptor before POST

My API's GET requests are polled at regular intervals. If I make a POST request while the GET request is pending and that POST returns with the new data, the data from the GET request will be outdated.

Using the HttpInterceptor can I cancel all pending GET requests before I send the POST?

I've been told that I can just not pass the req to the next.handle() but what req am I supposed to pass then?

Upvotes: 1

Views: 1884

Answers (1)

Vitalii Chmovzh
Vitalii Chmovzh

Reputation: 2943

If we talking about Angular 2, you probably call your API in the next way:

this.http.get('url').map(res => { ... }).catch(error => { ... });

It returns Observable and once you subscribe to it, it returns a subscription. Once you unsubscribe - it will cancel your request. See complete example:

service.ts

getData(): Observable<any> {
    return this.http.get('url').map(res => { ... }).catch(error => { ... });
}

component.ts

requestSubscription: Subscription;

ngOnInit() {
   this.requestSubscription = this.service.getData().subscribe(data => { ... });
}

someFuncWhereYouHandlePOSTSuccess() {
   if (this.requestSubscription) {
      this.requestSubscription.unsubscribe();
   }
}

Hope this concept is clear enough. If not - I'm ready to answer your questions.

Edit

Since the OP led me on the right path I figured my solution belongs next to his suggestion as the correct answer.

Solution service.ts

private breakPolling: boolean = false;

constructor(private httpClient: HttpClient) {
}

getData() {
    return this.httpClient
        .get(this.url)
        .map((response) => {
            if (this.breakPolling) {
                this.breakPolling = false;
                return Observable.empty();
            } else {
                return response;
            }
        });
}

breakPolling() {
    this.breakPolling = true;
    return Observable.empty();
}

I dispatch an action that will call the breakPolling() method and set a simple bool. Instead of returning the response data as an observable I just return an empty Observable.

It doesnt cancel the request, but it prevents its data from being passed on. Its ugly, but it'll patch.

Upvotes: 2

Related Questions