我有@ ngrx/store和效果正常,但是,我刚刚意识到会有很多API调用(在效果中),如果其中任何一个返回401错误,我应该将用户重定向到登录页面.我的问题是:我不想在每一个效果中都检查一下,这对同样的事情来说是一个额外的代码.比方说,我有一个像这样的代码:
样本效果
@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 }))
);
Run Code Online (Sandbox Code Playgroud)
userService.me()
me(): Observable<User> {
return this.apiService.get(`/auth/me`);
}
Run Code Online (Sandbox Code Playgroud)
apiService.get()
get(endpoint: string): Observable<any> {
return this.http.get(`${this.base}${endpoint}`, this.options())
.map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)
这很好用,但我不知道如何在API返回401时处理这种情况.在这种情况下,我应该在哪里全局重定向用户?我应该为该案件制定行动吗?那我应该在哪里发送这个动作呢?或者我完全错了吗?
任何正确方向的帮助将不胜感激!
car*_*ant 13
如果它们是从服务器接收的错误,则发出的错误Http将包含status属性(设置为HTTP状态代码).
如果在基于HTTP的服务故障操作中包含错误状态:
@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 }
}))
);
Run Code Online (Sandbox Code Playgroud)
然后,您可以编写一个通用效果,查看所有操作并重定向,如果它们包含401错误:
@Effect() errorStatus401$ = this.actions$
.map(action => action.payload)
.filter(payload => payload && payload.errorStatus === 401)
.switchMap(payload => {
this.router.navigate(['/login']);
return Observable.empty();
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用@ngrx/router-store:
import { go } from '@ngrx/router-store';
...
@Effect() errorStatus401$ = this.actions$
.map(action => action.payload)
.filter(payload => payload && payload.errorStatus === 401)
.map(payload => go(['/login']));
Run Code Online (Sandbox Code Playgroud)
如果您希望在导航之前执行其他操作,则可以使用concat以下命令发出多个操作:
@Effect() errorStatus401$ = this.actions$
.map(action => action.payload)
.filter(payload => payload && payload.errorStatus === 401)
.switchMap(payload => Observable.concat({ type: 'CLEAR_TOKEN' }, go(['/login'])));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2758 次 |
| 最近记录: |