简体   繁体   中英

Ionic 2 navigating from service when http request authorization fails

In my ionic 2 app I have 4 services that all make http request. Those services can be hit from 8 different pages in my app. I want to deal with the case that an authorization token is expired or removed or any variation of that. So if the user hits one of those services, and it returns a 401 Unauthorized error, how do I handle the error and navigate to my login page without having to put conditions on all 8 of those pages that use the services.

To reiterate : I would prefer to handle the error where the request is being made, in the service, and navigate to my login page from there, is this possible?

Are there better ways to handle this? Any advice would be appreciated.

Heres my desired flow:

  • On any page, make API request from one of my services (in service)
  • If the request returns an unauthorized error (in service)
    • clear user data (in service)
    • navigate to the login page (in service)
  • Else, (assume the request was successful)
    • parse/use the data in my page (in page)

You can use interceptor to check status code and if response comes 401, redirect to login page. I hope you must be knowing interceptor implementation

angular
    .module('myProject.myModule')
    .config(['$httpProvider', function ($httpProvider) {

 $httpProvider.interceptors.push(['$q', '$location', function ($q, $location) {
        return {
            'responseError': function(response) {
                if(response.status === 401) {
                    $location.path('/login'); 
                }
                if(response.status === 200) {
                    return $q.resolve(response);
                }
                return $q.reject(response);
            }
        };
    }]);
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM