Property 'forEach' does not exist on type 'Object'

19,400

It requires you to give it an explicit type for the request like so:

this.http.post<any[]>('...

According to Angular HttpClient Guide, HttpClient doesn't know what it is after parsing it from JSON so it assumes Object as the type of response, so typescript complains about that.

Share:
19,400
Jordan
Author by

Jordan

Updated on July 27, 2022

Comments

  • Jordan
    Jordan over 1 year

    I can't for the life of me figure out why I can't loop over the response from this http call. For whatever reason it's complaining that the type of data is an object, but when I console log it I can an array like I expect.

    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { URLSearchParams } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/forkJoin';
    
    promises.push(Observable.create(observer => {
        this.http.post(`items/event/${this.event.auction_code}`, body.toString(), {
            headers: new HttpHeaders().set('Content-Type', 'application/X-www-form-urlencoded' ),
        }).subscribe(data => {
           var classifiedData;
           data.forEach((item)=>{
              classifiedData.push(new Item(item));
           });
           observer.next(data);
           observer.complete();
        },error => {
           observer.throw(error);
        });
    }));
    ...
    Observable.forkJoin(promises).subscribe(results => {
       results.forEach((result,i)=>{
          data.content.template[i].data = result;
       });
    });
    

    Edit:

    Console.log shows me this

    enter image description here

    Edit: 2

    I also have an interceptor setup, could this be causing it?

    @Injectable()
    export class NoopInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const duplicate = req.clone({
          url: `${environment.apiUrl}/${req.url}`,
          params: req.params.set('key', environment.apiKey)
        });
        return next.handle(duplicate);
      }
    }