mat-autocomplete 适用于模拟数据。当我将它与实际服务集成时,它不会填充下拉列表。
我的 html 看起来像这样
<mat-form-field class="example-full-width">
<input
matInput
placeholder="LastName, FirstName"
aria-label="LastName, FirstName"
[matAutocomplete]="auto"
[formControl]="userCtrl"
/>
<mat-autocomplete #auto="matAutocomplete">
<mat-option
(click)="onSelect(user,i)"
*ngFor="let user of filteredUsers | async; let i = index"
[value]="user.name"
>
<span>{{ user.name }}</span>
<!-- <small> GUID: {{user.guid}}</small> -->
</mat-option>
</mat-autocomplete>
</mat-form-field>
组件如下所示
import {Component, Inject, ViewChild, OnInit} from '@angular/core';
import { MAT_DIALOG_DATA} from '@angular/material/dialog';
import { FormControl } from "@angular/forms";
import { Observable } from "rxjs";
import { map, startWith } from "rxjs/operators";
import { UserService } from '../../../shared/services/user/user.service';
@Component({
selector: "app-change-user-dialog",
templateUrl: "./change-user-dialog.component.html",
styleUrls: ["./change-user-dialog.component.scss"]
})
export class ChangeUserComponent implements OnInit {
userCtrl: FormControl;
filteredUsers: any;
selectedUser = "";
users = [
{
name: "Barrett, David",
guid: "1213123"
},
{
name: "Barrett, Elizabeth",
guid: "8437593"
},
{
name: "Barrett, Elizabeth",
guid: "2o934u124"
}
];
constructor( public dialogRef: MatDialogRef<ChangeUserDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: ChangeUserDialogComponent,
private userService: UserService ) {
this.userCtrl = new FormControl();
this.filteredUsers = this.userCtrl.valueChanges.pipe(
startWith(""),
map(user => (user.length >= 3 ? this.filterUsers(user) : []))
);
}
ngOnInit(): void {
}
filterUsers(name) {
this.users.filter((user) => {
return user.name.toLowerCase().indexOf(name.toLowerCase()) === 0
});
}
}
上面的组件工作正常,并显示带有模拟数据的下拉列表,
现在,我试图从服务中获取响应并将其分配回 this.users 并且它不起作用。
以下是我尝试过的
filterUsers(name: string) {
var split_str = name.split(",");
const lastname = split_str[0] ? split_str[0] : "";
const firstname = split_str[1] ? split_str[1] : "";
this.userService.getGuidByName(firstname, lastname).subscribe((data) => {
this.users = data;
return this.users.filter(
user => user.name.toLowerCase().indexOf(name.toLowerCase()) === 0
);
});
}
我的服务如下所示
public getGuidByName(firstname, lastname): Observable<any> {
return this.httpService.get('file', `/search?firstname=${firstname}&lastname=${lastname}`)
.pipe(
catchError(this.httpService.handleError('error'))
);
}
服务响应与我正在使用的模拟数据完全相同。
我错过了什么?任何输入表示赞赏。谢谢。