我想在文本框中实现自动完成功能,因为我已经创建了Web API,它返回了Json格式文件,但我得到了#34;找不到不同的支持对象' [object Object]'类型'对象'。 NgFor仅支持绑定到Iterables,例如Arrays。" 请帮我一下
我的代码:=
服务
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>
我的json文件如下
{&#34; ClientId&#34;:15,&#34; ClientName&#34;:&#34; Abhinav Singh&#34;}
答案 0 :(得分:1)
由于错误显示您的结果客户不是 array
,因此 object
, ngFor
< / strong>适用于 Objects
要解决此问题,请将您的JSON文件更改为
[{“ClientId”:15,“ClientName”:“Abhinav Singh”}]