我正在使用Angular 7,并且我想包括一个垫子自动完成搜索栏,其中包含通过API填充的芯片。 我的计划是拥有两个应用程序。一个与搜索有关,另一个与搜索结果有关。
我在这里遵循以下示例:https://material.angular.io/components/chips/examples(芯片自动完成功能) 现在,我想使用API数据重现相同的搜索工具。 数据为JSON格式,我已经编写了从API检索JSON的服务。 字段为{'id':数字,'name':字符串}。
这是执行的吧
<!-- Autocomplete search bar -->
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList aria-label="Name selection">
<mat-chip
*ngFor="let name of names"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(name)">
{{name}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input
placeholder="Search for Names..."
#fruitInput
[formControl]="nameCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let name of filteredNames | async" [value]="name">
{{name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
这是我正在使用的模型
export class chipsNameModel {
AchillesID: number;
CompanyName: string;
constructor(
AchillesID: number,
CompanyName: string
){
this.CompanyName = CompanyName;
this.AchillesID = AchillesID;
}//end of constructor
}
这就是我访问服务的方式
@Injectable({
providedIn: 'root'
})
export class SearchPageService {
constructor(private http: HttpClient) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
}
private objectReturn : any;
public getNames(): Observable<chipsNameModel[]>{
this.objectReturn = null;
var url =apiSearchModelAddress+"names/";
// console.log(url);
this.objectReturn = this.http.get<chipsNameModel[]>(url).pipe(
catchError(this.handleError('Name list issue',[]))
);
return this.objectReturn;
}
private handleError<T> (operation = 'operation', result?: T){
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
};
}
}
和与数据相关的应用的ts是
constructor(private namesData:SearchPageService) { }
names: Observable<chipsCompanyNameModel[]>;
ngOnInit() {
this.names = this.namesData.getNames();
}
我的目标是在搜索栏中查看API提供的选项,能够搜索并获得建议(自动完成),选择与我的搜索条件相对应的筹码,然后将输出发送到另一个应用程序以显示结果。
感谢您的帮助!