簡體   English   中英

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

[英]Angular 2, catching 401 in @ngrx/effects

我有@ 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'])));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM