【问题标题】:Cannot find a differ supporting object of type 'string'. NgFor only supports binding to Iterables such as Arrays找不到“字符串”类型的不同支持对象。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2021-07-01 16:07:56
【问题描述】:

我在运行 Angular 应用程序时遇到此错误 错误 错误:找不到不同的支持对象 '[{"distid":6,"stateid":12,"distname":"Uttarakannda"},{"distid":7,"stateid":12,"distname": '字符串'类型的“Udupi”}]'。 NgFor 只支持绑定到 Arrays 等 Iterables。

我不明白数组是如何转换成字符串的

代码:

服务文件

private districtURL = "http://localhost:8082/api/v1/districts";
...
getDistrictsList(stateid: number): Observable<Districts[]> {
    return this.httpClient.get<Districts[]>(`${this.districtURL}/${stateid}`);
  }

组件文件

districts: Districts[];
...
onChangeState(stateid: number){
    if (stateid) {
      this.landLoserService.getDistrictsList(stateid).subscribe(
        data => {
          this.districts = data;
          console.log(this.districts);

        }
      );
    } else {
      this.districts = null;
    }
  }

html文件

<select formControlName="state" [(ngModel)]="entry.state" (change)="onChangeState($event.target.value)">
                    <option value="" disabled selected></option>
                    <ng-container *ngFor="let state of states">
                      <option *ngIf="state.isactive==1" [value]="state.stateid">{{state.statename}}</option>
                    </ng-container>
</select>

<select formControlName="district" [(ngModel)]="entry.district">
                    <option value="" disabled selected></option>
                    <option *ngFor="let district of districts" [value]="district.distid">{{district.distname}}</option>
</select>

【问题讨论】:

  • 如果您正在获取字符串值,请尝试使用 JSON.parse 解析它,如下所示:this.districts = JSON.parse(data);
  • 我不知道它是如何转换成字符串的。在代码中,函数返回的是数组而不是字符串。
  • 您是否在网络选项卡中检查过响应?
  • 在网络选项卡中,您可以验证您是否从后端获取 json 或字符串

标签: angular typescript


【解决方案1】:

就在之前:

console.log(this.districts);

添加:

console.log(typeof data);

它会让您了解您收到的响应类型是什么。

理想情况下,服务器会处理响应类型,但如果它是字符串,您可能需要检查您发送的内容。

最后,如果您的应用无法解释响应类型,请尝试将请求标头设置为接受 JSON:

const headers = new HttpHeaders().set('Content-Type','application/json');
return this.httpClient.get<Districts[]>(`${this.districtURL}/${stateid}`, {headers: headers});

【讨论】:

  • 我重新启动了程序,它开始工作了。
  • 太棒了。有时是显而易见的解决方案。
猜你喜欢
  • 2017-07-29
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2020-06-11
  • 2020-08-29
  • 2018-07-14
  • 2017-02-10
相关资源
最近更新 更多