簡體   English   中英

在 rxjs catchError() 之后,Angular POST 請求未將結果傳回

[英]Angular POST request not passing result back after rxjs catchError()

我正在嘗試使用 catchError 在 POST 方法中捕獲錯誤。 但是,當我收到無效響應(例如登錄失敗)時,代碼會執行 catchError() (打印 console.log),但我從未看到來自訂閱的控制台消息“已收到登錄結果”。 為什么 catchError 不將值傳遞回訂閱? 請注意,當登錄成功時,一切都按預期工作(console.log 打印正確)

this.auth.login(this.model.username, this.model.password).subscribe(x=>{ 
  console.log('login result received');
  this.loading=false });

我的服務:

login(username: string, password: string): Observable<boolean> {
    return this.http.post<TokenResponse>('/api/auth/token', { name: username, password: password }).pipe(
        catchError(this.appSvc.handleError<boolean>("auth/login", false)),
        map((response: TokenResponse) => {
            if (response !=null) {
                // do token things
                return true;
            }
            else
                alert('rxjs token null')
        }
        ));
}             

public handleError<T>(operation = 'operation', result?: T){
  console.log('got here');
  return of(result as T);}

您在管道中錯誤地使用了catchError 應該:

catchError(error => this.appSvc.handleError<boolean>("auth/login", false))

另請參閱此處包含工作代碼的 Stackblitz: https ://stackblitz.com/edit/angular-hugqem

結果是 catchError (布爾值)的結果被傳遞給 map 因為 catchError 被觸發,然后 map 試圖映射結果。 就我而言

  1. catchError 返回一個布爾值
  2. map 正在尋找 TokenResponse 類型的對象,但沒有找到。 所以地圖什么也沒返回。

我的解決方法是:

  1. 將 map 預期的類型從“TokenResponse”更改為“any”
  2. 捕捉響應類型為布爾值的情況(else if 語句)

完整代碼:

login(username: string, password: string): Observable<boolean> {
    return this.http.post<TokenResponse>('/api/auth/token', { name: username, password: password }).pipe(
        catchError(this.appSvc.handleError<boolean>("auth/login", false)),
        map((response: any) => {
            if (response.token !=null) {
                // do token things
                return true;
            }
            else if (typeof response==="boolean") //note that catcherror will pass its return type (bool) to here
                    return false
            else
                alert('rxjs token null')
        }
        ));
}   

暫無
暫無

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

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