Reputation: 453
I wanted to implement Autocomplete functionality on text box for that i have created web API which returns Json format file but I am getting "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." please help me in same
My code:=
Service
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class ClientSearchService {
endPoint: string;
constructor(private http: Http) {
this.endPoint = "http://localhost:57888/api/Employees/GetEmployeeById";
}
search(term: string): Observable<any[]> {
var ClientList = this.http.get(this.endPoint + '/' + term)
.map((r: Response) => { return (r.json().length != 0 ? r.json() : [{ "ClientId": 0, "ClientName": "No Record Found" }]) as any[] });
return ClientList;
}
}
app component.ts
import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { ClientSearchService } from './_services/client-search.service';
@Component({
selector: 'client-search',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
public clients: Observable<any[]>;
private searchTerms = new Subject<string>();
public ClientName = '';
public flag: boolean = true;
constructor(
private clientSearchService: ClientSearchService,
) {
}
ngOnInit(): void {
this.clients = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term
? this.clientSearchService.search(term)
: Observable.of<any[]>([]))
.catch(error => {
console.log(error);
return Observable.of<any[]>([]);
});
}
searchClient(term: string): void {
this.flag = true;
this.searchTerms.next(term);
}
onselectClient(ClientObj) {
if (ClientObj.ClientId != 0) {
this.ClientName = ClientObj.ClientName;
this.flag = false;
}
else {
return false;
}
}
}
HTML
</div>
</div>
<div class="search-result" *ngIf="flag">
<ul>
<li *ngFor="let client of clients | async">
//<a (click)="onselectClient(client)">{{client.ClientName}}</a>
</li>
</ul>
</div>
My json file is as below
{"ClientId":15,"ClientName":"Abhinav Singh"}
Upvotes: 0
Views: 742
Reputation: 222522
As the error says your result clients is not an array
, its an object
, ngFor
works over an array of Objects
To fix it , change your JSON file as
[{"ClientId":15,"ClientName":"Abhinav Singh"}]
Upvotes: 1