Using Interceptors to Handle Location Services in an Ionic Angular App

Hey there fellow developers! This is my very first article, and I’m thrilled to share it with you. Today, I’m going to talk about a use case where I used Angular HTTP interceptors to solve a tricky problem in a mobile app built with the Ionic framework. Let’s dive in!

The Problem I Faced

The app I’m working on depends heavily on location services to provide essential features. For the app to function properly, it’s important that location services stay enabled. Here’s what I ran into:

  1. Initial Issue: When users opened the app with location services turned off, they weren’t prompted to enable them.

  2. Dynamic Issue: If users disabled location services while using the app, there was no way to detect it and respond appropriately.

I needed a way to:

  • Show a non-dismissible popup asking users to enable location services when needed.

  • Detect dynamically if users turned location services on or off while using the app.

My First Attempt: SetInterval

At first, I used the Geolocation API’s checkLocationPermissions() method to check location permissions. If location services were disabled, the API would throw an exception, and I could handle it accordingly.

To detect changes dynamically, I used setInterval to run the location check every five seconds. While this worked, it had some major drawback:

  • Performance Issues: The app kept running the location check even when location services were enabled, wasting resources.

I realized i needed a better approach as this one was killing the performance of the app

The Optimized Solution: HTTP Interceptors

After consulting with a senior engineer on my team, I learned about Angular HTTP interceptors. They turned out to be the perfect solution for my problem.

What is HTTP interceptor in angular?

Interceptors in Angular allow you to intercept a HTTP requests so you can maybe inspect it or transform it and in my case to trigger a certain action on every request.

Approach:

I used the Geolocation API's checkLocationPermissions() method to check location permissions. I wrapped this logic inside a reusable function to handle showing a non-dismissible popup when location services are disabled. Then, I created an Angular HTTP interceptor and called this function inside the intercept method. The interceptor dynamically checks location status whenever an HTTP request is made, and if location services are disabled, it prevents the request and shows the popup. Problem solved!