typescript “对象”类型上不存在属性“forEach”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46352289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:54:40  来源:igfitidea点击:

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

angulartypescriptrxjs

提问by Jordan

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 datais an object, but when I console log it I can an array like I expect.

我终其一生都无法弄清楚为什么我无法遍历来自此 http 调用的响应。无论出于何种原因,它都抱怨类型data是一个对象,但是当我控制台记录它时,我可以像我期望的那样使用数组。

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

Console.log 显示我这个

enter image description here

在此处输入图片说明

Edit: 2

编辑: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);
  }
}

回答by lenilsondc

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

它要求您为请求提供一个明确的类型,如下所示:

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

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

根据Angular HttpClient GuideHttpClient从 JSON 解析后不知道它是什么,所以它假定Object为响应类型,所以打字稿抱怨。