-1

I have a function that does a HTTP post on click of a Submit button. Based on the response I will display a modal saying the request was success or not.

Now the problem arises when the user clicks on the Submit button and immediately clicks on a navigation icon that will load a different component. Now the other page is loaded but still the HTTP request is processed and resolve/reject is called and the modal backdrop fade is displayed which grays out the whole screen and does not allow the user to do anything else. The only way out is to refresh the screen.

Is there a way I can stop executing the resolve / reject onDestroy of the component?

Sara
  • 33
  • 1
  • 10
  • Does this answer your question? [How to cancel a HTTPRequest in Angular 2?](https://stackoverflow.com/questions/36490926/how-to-cancel-a-httprequest-in-angular-2) – Armen Stepanyan Jan 17 '20 at 08:40
  • 1
    Use Observables from RxJS & use unsubscribe method. – Pawan Kumar Jan 17 '20 at 08:42
  • 1
    This will help you. Using takeuntill and Unsubscribe https://stackoverflow.com/questions/46068908/how-to-cancel-unsubscribe-all-pending-http-requests-angular-4 – uiTeam324 Jan 17 '20 at 08:44
  • Checkout this link, it would be helpful : https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163#41177163 – Mukund Sonaiya Jan 17 '20 at 08:54
  • The take(1) or takeUntil did not help. The request has already fired and the above does not stop the same. – Sara Jan 17 '20 at 09:17
  • If you started a network request, you can't cancel that, ie. you can't create another request to the server saying 'hey, cancel the other one'. What you can do with the `unsubscribe` or `takeUntil` is that even though the network requests will be answered by the backend, your subscribe method won't be called, so the dialog won't be displayed. Also, don't mix up `unsubscribe` and `takeUntil` with `take(1)` in this regard, because the first 2 can actually prevent the method in subscribe to be called, but with `take(1)` it will definitely be called (unless the request returns an error). – Alex Biro Jan 17 '20 at 09:21

1 Answers1

2

I use this

export class Component implements OnInit, OnDestroy {
    alive = true;
    constructor(
        private route: ActivatedRoute,
        private router: Router
    ) { }

    ngOnInit() {
        this.route.queryParamMap //example observable
            .pipe(
                takeWhile(() => this.alive)
            )
            .subscribe(params => {

            });
    }

    ngOnDestroy(): void {
        this.alive = false;
    }
}

Also you in your redirect button (I suppose that the redirect is in you modal if you have backdrop implemented) you should set the backdrop to false.

anthony willis muñoz
  • 2,346
  • 3
  • 16
  • 33
  • Both takeWhile and Unsubscribe works. Was struck with TakeUntil and Take(1). Thanks. – Sara Jan 17 '20 at 09:20