gpt4 book ai didi

javascript - (Angular) 拦截 HttpResponse 错误并继续 Observable

转载 作者:行者123 更新时间:2023-12-05 05:49:29 25 4
gpt4 key购买 nike

我有一个下拉文本框,可以进行预输入搜索。当我搜索有效的项目名称(存在于数据库中)时,搜索工作正常并返回下拉列表中的项目列表,供我在键入时从中选择。但是当我搜索无效文本时,API 返回 400 错误(这很好),然后是 HttpErrorInterceptorcatchError() 中拦截该响应方法,并抛出一个错误弹出窗口。我不想要错误弹出窗口,我希望它将错误转发给文本框逻辑,这样我就可以在下拉列表中显示“未找到任何项目”。

文本框 html(使用 Angular 的 NgbTypeahead):

      <input
id="searchText"
type="text"
[(ngModel)]="selectedItem"
(selectItem)="onSelectItem($event)"
formControlName="searchText"
[ngbTypeahead]="search"
#instance="ngbTypeahead" />

文本框逻辑:

  search = (input: Observable<string>) => {
return input.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap((text) => text.length < 2 ? this.clearItems() //clearItems() is irrelavant
: this.itemService.getItemSearchData(text).pipe(
map(responseObj => {
const itemList = responseObj.data ? orderBy(responseObj.data, ['itemName'], ['asc']) : [];

if (itemList.length === 0) {

// this is what I want it to do when I get the error response
itemList.push({ itemName: 'No Items Found' } as ItemList);
}
return itemList;
})
)));
}

// This is in the ItemService class.
getItemSearchData(searchTerm: string): Observable<any> {
const searchItem = {
"filterBy": {
"key": "itemname",
"value": searchTerm
}
}

return this.http.post(this.itemApiUrl, searchItem, { headers: this.headers });
}

这是拦截器:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private matDialog: MatDialog) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMessage = 'Unknown error!';
if (error.error instanceof ErrorEvent) {
errorMessage = `Error: ${error.error.message}`;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}

// the error popup. I DON'T want to throw this when I get the 404 response.
this.matDialog.open(PopupComponent, {
data: { actionDesctiption: errorMessage, isError: true },
panelClass: 'custom-dialog-container'
});

return throwError(error);
})
);
}

我试过这个:Angular: intercept HTTP errors and continue chain , 但顶级解决方案的 return of(new HttpResponse...;语句给了我错误 Type 'Observable<unknown>' is not assignable to type 'Observable<HttpEvent<any>>' .我也试过返回 next.handle(request)new Observable<HttpEvent<any>>() .

当我在 map(responseObj => 处放置断点时行,它总是说“responseObj 未定义”。

当 API 返回 400 错误时,如何让下拉列表显示“未找到任何项目”?

最佳答案

不清楚从您的 API 返回的数据的结构是什么。假设 API 以这种格式返回数据:{ itemName: string }[](即 { itemName: string } 对象的数组,您可以使用 http 拦截器来检查对于 404 错误,然后像这样更改响应:

import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { of, throwError } from 'rxjs';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private matDialog: MatDialog) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error) => {
let errorMessage = 'Unknown error!';
if (error.error instanceof ErrorEvent) {
errorMessage = `Error: ${error.error.message}`;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}

// check for a 404 error response
if (error instanceof HttpErrorResponse && error.status === 404) {
return this.returnCustomData([{ itemName: 'No Items Found' }]); // returns a response, and doesn't throw the error
}

// the error popup. I DON'T want to throw this when I get the 404 response.
this.matDialog.open(PopupComponent, {
data: { actionDesctiption: errorMessage, isError: true },
panelClass: 'custom-dialog-container'
});

return throwError(error);
})
);
}

private returnCustomData(body) {
return of(new HttpResponse({ status: 200, body }));
}

}

注意:同样,我假设您的 API 返回一组 { itemName: string } 对象,这就是我在调用时在数组中使用一个对象的原因返回自定义数据。请记住更改发送到 returnCustomData 的数据对象以匹配您的 API 返回的实际数据格式,就好像它只返回一个结果,包含“No Items Found”字样。

关于javascript - (Angular) 拦截 HttpResponse 错误并继续 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70660345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com