微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 2,在@ ngrx / effects中捕获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'])));

原文地址:https://www.jb51.cc/angularjs/141416.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐