How to handle 401 expired token in Ionic 2 nicely?

i would use Subjects, because you can:

  1. subscribe subjects like observables
  2. push new values

So you have a service, which is your baserequest service, any other service that wants to send an request, does not use HTTP directly.

This base request service holds an subject.
A base-component or App subscribes this subject.
If there is an error or 401 to handle --> your service triggers with subject.next() all subscribers.

So now you app knows, when an error occurs and gets informed. Now your base page/component can open an alert with the new credential check. When alert.dismiss(); is called you can check, if logged in or not and handle the redirect.

Your base request service need a flag, that says “hey, i am waiting for credentials”, because there are maybe other requests in the meantime. So you have an Array of pending requests --> if you are logged in again, resend all pending requests.

2 Likes