我正在嘗試與此 api 進行通信,如果我請求 api/all url,則使用物件陣列回應,或者如果我使用 /api/ 請求特定元素,則使用單個物件進行回應
在第二種情況下,我使用 HTTPInterceptor 將回應作為一個僅包含該物件的陣列,如下所示:
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
tap(response => {
if (response instanceof HttpResponse && typeof response.body === 'object') {
console.log(response.clone({body: [response.body]}))
return response.clone({body: [response.body]})
}
return response
})
);
}
一切正常,除了在我的組件中我需要將此物件映射到介面中,我這樣做是這樣的:
ngOnChanges(changes: SimpleChanges) {
this.getFruits(this.filter)
}
ngOnInit(){
this.getFruits()
}
getFruits(fruitName = 'all') : void{
this.fruityService.getFruits(fruitName).subscribe( response => {
this.fruits = response.map(fruit => ({
name: fruit.name,
id : fruit.id,
nutritions : fruit.nutritions
}))
})
當我請求使用單個專案設定過濾器時,我收到此錯誤,例如回應不是陣列
ERROR TypeError: response.map is not a function
關于我在這里做錯了什么的任何提示?有比我實施的更好的解決方案嗎?
uj5u.com熱心網友回復:
你用tap,但它應該是map。tap不會改變管道值。
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
map(response => { // <-- CHANGE TO MAP HERE
if (response instanceof HttpResponse && typeof response.body === 'object') {
console.log(response.clone({body: [response.body]}))
return response.clone({body: [response.body]})
}
return response
})
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522007.html
標籤:有角度的打字稿rxjs
