Reputation: 1927
I'm having a nodejs (express) as a server side and an angular 6 as client.In the server I have middlewear function that makes a session check. In case where the session is invalid or not exists, I would like to send a response to the client so that it can react to it. I thought of returning a response code of 401 from the server, and make some kind of listener\route-guard\HttpInterceptor in the client, so - it can manage the situation in the client (redirect it to the login page, for example). Here is my code in the server:
router.use('/', (req, res, next) =>
{
if (!req.session.user)
{
res.status(401);
}
else{
next();
}
})
How can I catch\listen to this response in the angular app ?
Upvotes: 2
Views: 6527
Reputation: 5194
There are two parameters present when you hit http calls . First : the success callback . Second : the error callback.
for example if we have a service named api
below will be the complete code :
if you need to capture the error in service:
getData(){
this._http.get(url).map((response: Response) =>{
return response.json();
})
.catch(this.handelError)
}
handelError(error: Response){
console.log('got below error from server',error);
}
If you need to capture error in component:
someMethod(){
this._apiService.getData().susbscribe((result)=>{
console.log('sucess',result);
// do further processing
},(error)=>{
console.log('error from service',error);
// do further processing
});
}
Upvotes: 2
Reputation: 1601
You can create an HttpInterceptor
in which you can check wether status is 401, if yes then logout user and redirect to login page. What HttpInterceptor
do is intercept every request and response and allow you to do some specific action like checking if servce returned 401 status. However be aware of range
for interceptor
it's working like services
so if you include it in your top level module then it will intercept every request and response
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private authService: AuthService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
map((event: HttpEvent<any>) => event), // pass further respone
catchError((error: HttpErrorResponse) => {
// here will be catched error from response, just check if its 401
if (error && error.status == 401)
// then logout e.g. this.authService.logout()
return throwError(error);
}));
}
}
And then include it in app.httpmodule
in providers section
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
]
Read more at angular.io docs or angular.io guide
Upvotes: 5