gpt4 book ai didi

来自 API 的 Angular Material 自动完成

转载 作者:行者123 更新时间:2023-12-03 19:44:17 26 4
gpt4 key购买 nike

我尝试从 api 使用自动完成,但它不起作用。
它只有在没有 api 的情况下才能工作。

这是我的组件 TS:在那里,有一个带有来自 api (onGetTaxList) 的数据的回调方法

import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../../../core/services/users.service';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
selector: 'app-create-process-modal',
templateUrl: './create-process-modal.component.html',
styleUrls: ['./create-process-modal.component.sass']
})
export class CreateProcessComponent implements OnInit {
myControl = new FormControl();
options = [
{ name: 'One' },
{ name: 'Two' },
{ name: 'Tree' },
];
filteredOptions: Observable<any>;


constructor(private service: UsersService) { }

ngOnInit() {
this.service.createNewProcess((data) => this.onGetTaxList(data));
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}

onGetTaxList(data) {
console.log(data);
}
private _filter(value: string) {
const filterValue = value.toLowerCase();

return this.options.filter(option => option.name.toLowerCase().includes(filterValue));
}
}


组件html:

<div class="formContainer">
<h2 style="text-align: right">New Process</h2>
<mat-form-field style="text-align: right">
<input type="text" placeholder="Start Typing..." matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>

</div>


在这种状态下它与对象的工作
options = [
{ name: 'One' },
{ name: 'Two' },
{ name: 'Tree' },
];

现在我想从数据 api 中获得它的工作:
0: {companyName: "ziro", cid: "524023240", partners: Array(4)}
1: {companyName: "plus", cid: "524023240", partners: Array(2)}

我需要自动完成过滤器公司名称。
谢谢。

最佳答案

成分:

  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
}))
)
}
}
服务:
opts = [];

getData() {
return this.opts.length ?
of(this.opts) :
this.http.get<any>('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
}

要查看完整演示,请查看此链接 Stackblitz

关于来自 API 的 Angular Material 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57852645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com