Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
  }
}
like image 282
Jordan Avatar asked Sep 21 '17 20:09

Jordan


People also ask

How do you fix property does not exist on type?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names. Copied!

Does not exist on type unknown TS 2339?

To fix the error "TS2339: Property 'x' does not exist on type 'Y'" with TypeScript, we should make sure the properties are listed in the interface that's set as the type of the object. interface Images { main: string; [key: string]: string; } const getMainImageUrl = (images: Images): string => { return images. main; };


1 Answers

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.

like image 89
lenilsondc Avatar answered Dec 23 '22 15:12

lenilsondc