Angular 2, catching 401 in @ngrx/effects -


i've got @ngrx/store , effects working fine, however, realized there a lot of api calls (in effects), , if of returns 401 error should redirect user login page. problem is: don't want check in every single effect, ton code same thing. let's example have code this:

sample effect

@effect() getme$ = this.actions$     .oftype(get_me)     .map(action => action.payload)     .switchmap(payload => this.userservice.me()         .map(res => ({ type: get_me_success, payload: res }))         .catch(() => observable.of({ type: get_me_failure }))     ); 

userservice.me()

me(): observable<user> {   return this.apiservice.get(`/auth/me`); } 

apiservice.get()

get(endpoint: string): observable<any> {   return this.http.get(`${this.base}${endpoint}`, this.options())     .map(res => res.json()); } 

this works fine, i'm not sure how handle case when api return 401. should redirect user globally in case? should create action case? should dispatch action then? or doing wrong?

any in right direction appreciated!

the errors emitted http contain status property (set http status code) if errors received server.

if include error status in http-based service failure actions:

@effect() getme$ = this.actions$     .oftype(get_me)     .map(action => action.payload)     .switchmap(payload => this.userservice.me()         .map(res => ({ type: get_me_success, payload: res }))         .catch(error => observable.of({             type: get_me_failure,             payload: { errorstatus: error.status }         }))     ); 

you write general-purpose effect looks @ all actions , redirects if contain 401 error:

@effect() errorstatus401$ = this.actions$     .map(action => action.payload)     .filter(payload => payload && payload.errorstatus === 401)     .switchmap(payload => {         this.router.navigate(['/login']);         return observable.empty();     }); 

or, if use @ngrx/router-store:

import { go } '@ngrx/router-store'; ...  @effect() errorstatus401$ = this.actions$     .map(action => action.payload)     .filter(payload => payload && payload.errorstatus === 401)     .map(payload => go(['/login'])); 

if there additional actions wish perform before navigating, can emit multiple actions using concat:

@effect() errorstatus401$ = this.actions$     .map(action => action.payload)     .filter(payload => payload && payload.errorstatus === 401)     .switchmap(payload => observable.concat({ type: 'clear_token' }, go(['/login']))); 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -