Handling 401s globally with Angular

后端 未结 8 979
误落风尘
误落风尘 2020-11-28 18:50

In my Angular 2 project I make API calls from services that return an Observable. The calling code then subscribes to this observable. For example:

getCampai         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 19:29

    The Observable you get from each request method is of type Observable. The Response object, has an status property which will hold the 401 IF the server returned that code. So you might want to retrieve that before mapping it or converting it.

    If you want to avoid doing this functionality on each call you might have to extend Angular 2's Http class and inject your own implementation of it that calls the parent (super) for the regular Http functionality and then handle the 401 error before returning the object.

    See:

    https://angular.io/docs/ts/latest/api/http/index/Response-class.html

提交回复
热议问题