and*_*ula 11 rest angular-material2 angular
我正在使用角5和材料2.
在ts文件中,我有这个专业:
filteredOptions: Observable<any[]>;
Run Code Online (Sandbox Code Playgroud)
此属性将具有要在自动填充字段中显示的值数组.
[{
id:'1', name: 'teste 1'},
{id:'2', name: 'teste 2'},
{id:'3', name: 'teste 3'
}]
Run Code Online (Sandbox Code Playgroud)
这个值数组来自数据库,它将在用户输入内容后显示.
html文件:
## <form class="example-form">
## <mat-form-field class="example-full-width">
## <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
## <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
## <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
## {{ option.name }}
## </mat-option>
## </mat-autocomplete>
## </mat-form-field>
## </form>
Run Code Online (Sandbox Code Playgroud)
ts文件示例:
this.filteredOptions = Observable<any[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith({}),
map(getArrayOfValue(val))
);
}
// it is going to call an api to get the array of values to be shown in the field
getArrayOfValue(val): Observable<any[]> {
const url = this.ROOT_URL + 'veiculo/' + val;
return this.http.get<any[]>(url);
}
Run Code Online (Sandbox Code Playgroud)
这段代码给我一个错误
src/app/oficina/cadastro/veiculo/veiculo.component.ts(55,5)中的错误:错误TS2322:类型'Observable>'不能分配给'Observable'类型.类型'Observable'不能分配给'any []'.'Observable'类型中缺少属性'includes'
AJT*_*T82 21
我看到一些问题,例如你应该map(val => this.getArrayOfValue(val)).但我还建议一些额外的改变.考虑添加debounceTime,distinctUntilChanged和switchMap.设置您选择的去抖时间.这,不要完全超载api.以及switchMap有助于将请求切换到用户键入的最后一个值.您还应考虑为api请求使用服务,这通常是我们处理事务的方式.所以我建议将http请求移动到服务并从组件中调用它.
TS:
// inject your created service which makes the http-request
constructor(private service: Service) {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
debounceTime(400),
distinctUntilChanged(),
switchMap(val => {
return this.filter(val || '')
})
);
}
// filter and return the values
filter(val: string): Observable<any[]> {
// call the service which makes the http-request
return this.service.getData()
.pipe(
map(response => response.filter(option => {
return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
}))
)
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您似乎value在模板中使用您的选项.如果要捕获整个对象,请使用[value].
这是一个你可以玩的演示 :)
| 归档时间: |
|
| 查看次数: |
13236 次 |
| 最近记录: |