A common design pattern you might come across in Ionic is wanting to perform some kind of UI-based action from within a service. For example, if an API request returns a 403 / not authorised header, you’ll want to display an alert and redirect to a login page. It’s not DRY to repeat the alert / redirect code on every single component that calls the API, so you might feel like doing this from within the service itself. This is Bad Practice™. Services should only deal with data and shouldn’t interact with the view.
So what can we do? Luckily there’s an easy way to solve this problem using observables. Here’s a simple example of an ApiService with an observable for errors:
Then, in app.component.ts, we subscribe to the error observable. From here we can use the AlertController and NavController to perform the relevant actions, but for the sake of simplicity I’ve just added some comments.
I’d like to thank sebaferreras from Stack Overflow for his answer that helped me develop my solution.
Comments are closed.
1 comment
fantastic, many thanks <3