【问题标题】:Property 'forEach' does not exist on type 'Object'“对象”类型上不存在属性“forEach”
【发布时间】:2018-03-03 07:11:22
【问题描述】:

我一辈子都想不通为什么我不能遍历这个 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;
   });
});

编辑:

Console.log 显示这个

编辑:2

我也设置了拦截器,会不会是这个原因?

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

【问题讨论】:

  • 似乎不是您期望的数组。 console.log(data) 打印什么?
  • 我仍然收到Property 'map' does not exist on type 'Object'.。就像我提到的,控制台注销data 在控制台中显示一个数组。
  • 用我在控制台中看到的屏幕截图更新了问题
  • 乔丹,如果只是错字问题考虑删除它。
  • 所以我实际上想知道 Visual Studio 和 CLI 如何知道从该端点返回的数据不是数组?因为当我查看来自服务器的实际数据时,它看起来是一个合适的数组

标签: angular typescript rxjs


【解决方案1】:

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

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

根据Angular HttpClient GuideHttpClient 在从 JSON 解析后不知道它是什么,因此它假定 Object 作为响应类型,因此 typescript 抱怨这一点。

【讨论】:

    【解决方案2】:

    对象可能缺少显式数组语法。例如,如果错误出现在这一行

    this.subscriptions.forEach(...);

    检查“订阅”的定义位置

    之前

    private subscriptions: Subscription;

    之后

    private subscriptions: Subscription[];

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多