Home > database >  can't use response.map on Intercepted an modified response Angular
can't use response.map on Intercepted an modified response Angular

Time:10-28

I'm trying to communicate with this api that responds either with an array of objects if I request the api/all url, or with a single object if I request a specific element with /api/

In the second case I'm using an HTTPInterceptor to make the response as an array containing only that object like this:

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

      })
    );
  }

Everything works fine except that in my component I need to map this object into an interface and I'm doing it like this:

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
      }))
    })

When I request a single item setting the filter with I get this error like the response is not an array

ERROR TypeError: response.map is not a function

Any hints on what I'm doing wrong here? Is there a better solution then the one I've implemented?

CodePudding user response:

You use tap, but it should be map. tap doesn't alter the piped value.

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

      })
    );
  }
  • Related