Calling Webapi on Chaging routes

15 views
Skip to first unread message

Dhimant Bhensdadia

unread,
May 31, 2019, 1:35:05 PM5/31/19
to Angular and AngularJS discussion
I have two page with two components:


PAGES:
HOME & ABOUT 

with two components

COMPONENTS:
Home.component & About.component

When I redirect from Home to About page and vice versa, I want to call a Webapi before it routes to another page

I have tried 2 things:

1. ngOnDestroy
2. Subscribe Router Events


Example: Let's say I am navigating from Home => About page, so inside the home component method, Below are the two cases 


Home.component.ts :::: Calling Webapi method inside ngOnDestroy method.

------------------------------------------ ngOnDestroy ---------------------------------------------------------

public ngOnDestroy(): void {
        
        this.updateChanges(); // Indside this method http call is there
        
        // Unsubscribe from all subscriptions
        this._unsubscribeAll.next();
        this._unsubscribeAll.complete();
}

----------------------------------------------- Router ------------------------------------------------------------

Home.component.ts :::: Calling Webapi by Subscribing Router change events

public ngOnDestroy(): void {

this._router.events.subscribe((ev: Event) => {
           if (ev instanceof NavigationStart) {
                this.updateChanges(); // Indside this method http call is there
           }
        }
);
}

---------------------------------------------------------------------------------------------------------------------

PROBLEM is: Inside network tab in browser I can see that Webapi is getting called but status is showing Cancelled. Any idea why?


Sander Elias

unread,
Jun 7, 2019, 1:53:49 AM6/7/19
to Angular and AngularJS discussion
Hi Dhimant,

Http is async, and if the caller gets destroyed, the call will get canceled. This is a key feature of Observables.
In both cases, the caller gets thrown away before the results can come in. That is the reason you calls are aborted.

A better approach to this would be a ca(de)activate guard.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages