0
votes

I am getting this error while running my Angular application ERROR Error: Cannot find a differ supporting object '[{"distid":6,"stateid":12,"distname":"Uttarakannda"},{"distid":7,"stateid":12,"distname":"Udupi"}]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

I don't understand how the array is getting converted into String

Code:

service file

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

component file

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 file

<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>
1
If you are getting string value then try to parse it using JSON.parse something like this:this.districts = JSON.parse(data); - Chellappan வ
I don't know how it is getting converted into string. In the code, the function is returning an array not a string. - Kanupriya Ishu
Have you checked response in network tab? - Chellappan வ
In network tab you can verify whether you getting json or string from back end - Chellappan வ

1 Answers

0
votes

Just before:

console.log(this.districts);

Add:

console.log(typeof data);

It'll give you the idea of what is the type of response you're getting.

Ideally the server takes care of the response-type but if it's string you might need to check what you're sending.

Lastly, try setting the request header to accept JSON if your app is unable to interpret the response type:

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