Check if back button was used (Ionic 4)

Hi all,

I am trying to work out how I can check if the route was loaded programmatically or if the back button was clicked / pressed instead. I have done some searching but I can’t seem to find anything that is relevant, and the route params don’t seem to contain anything to help my check either.

My reason for this is when my page is loaded we do an API call to retrieve a list of items, but after you click through to the item page then click Back, it does the API call again (using ionViewWillEnter hook).

I could just have the API call in the constructor method so it’s only done once, but in most cases when someone is routed to the page (for example using this.router.navigate(['list']) I actually do want it to trigger so ionViewWillEnter makes more sense.

Any help would be appreciated! Or perhaps a better way of looking at this?

You could maybe, at first api call success store a truthy value in localstorage. check if the that value exist then ignore calling the api. :sweat_smile:

I would suggest moving all backend-related logic to service providers and completely out of pages. That way you are in charge of all timing and caching issues, and not at the mercy of any lifecycle events.

@rapropos It basically is seperated already - all that lifecycle event does is call a method in my api service:

ionViewWillEnter() {
    this.listId = this.route.snapshot.paramMap.get('id');
    this.api.getList(listId).then((list) => {
            this.list = list;           

Or am I misunderstanding your comment? At some point when that page is loaded I do need to do fire off that API call.

The way that I do this is to have service providers expose an Observable<Thingy[]>, which is usually implemented in the provider as a Subject<Thingy[]>. So your page subscribes to that Observable in ionViewWillEnter() and unsubscribes in ionViewWillLeave() (or other equivalent pair of events).

The service provider is therefore in charge of when the actual backend is hit, and the timing of that is totally up to you. Typically, I do that once at service provider construction and then also expose a refresh() method in the provider that can be called when, for example, a user manually hits a refresh button. refresh() ends up calling next() on the provider’s internal Subject, which means that all consumers (including the page containing the refresh button) get notified of new data via their subscriptions without additional effort on their part.

Thanks @rapropos that lead me down the right path! Using a separate provider class with a flag to reload the api or just return the previous list was perfect