加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2,在@ ngrx / effects中捕获401

发布时间:2020-12-17 08:20:29 所属栏目:安全 来源:网络整理
导读:我有@ ngrx / store和效果很好,但是,我刚刚意识到会有很多API调用(在效果中),如果其中任何一个返回401错误,我应该将用户重定向到登录页面.我的问题是:我不想在每一个效果中检查一下,这对于同样的事情来说是一个额外的代码.比方说,我有一个像这样的代码: 样
我有@ 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 }))
    );

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());
}

这工作得很好,但我不知道如何在API返回401时处理这种情况.在这种情况下,我应该在哪里全局重定向用户?我应该为该案件制定行动吗?那我应该在哪里发送这个动作呢?或者我完全错了吗?

任何正确方向的帮助将不胜感激!

如果它们是从服务器接收的错误,则从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 }
        }))
    );

然后,您可以编写一个通用效果,查看所有操作并重定向,如果它们包含401错误:

@Effect() errorStatus401$= this.actions$
    .map(action => action.payload)
    .filter(payload => payload && payload.errorStatus === 401)
    .switchMap(payload => {
        this.router.navigate(['/login']);
        return Observable.empty();
    });

或者,如果您使用@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']));

如果您希望在导航之前执行其他操作,则可以使用concat发出多个操作:

@Effect() errorStatus401$= this.actions$
    .map(action => action.payload)
    .filter(payload => payload && payload.errorStatus === 401)
    .switchMap(payload => Observable.concat({ type: 'CLEAR_TOKEN' },go(['/login'])));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读