Angular Mat AutoComplete 不显示/显示从后端返回的对象的下拉列表

Posted

技术标签:

【中文标题】Angular Mat AutoComplete 不显示/显示从后端返回的对象的下拉列表【英文标题】:Angular Mat AutoComplete doesn't display/show drop down list of returned Object from Back End 【发布时间】:2018-11-05 00:51:07 【问题描述】:

我已经尝试实现 mat 自动完成(Angular Material)并且 .TS 代码可以工作并从我的后端 API 返回数据。 但是自动完成不会在下拉列表中自动显示对象。

按照我的代码:

export class VendaComponent implements OnInit 

  public produtoAutoComplete: Observable<Produtos> = null;
  public vendaForm = new FormControl();
  vendas: Venda[] = [];
  produtos:Produtos;
  isLoading = false;

  constructor(private vendasService: VendaService, private produtoService: ProdutoService, private toastr: ToastrService)  

  lookup(value: string): Observable<Produtos> 
    return this.produtoService.search(value.toLowerCase()).pipe(
      // map the item property of the github results as our return object
      map(results => results.produtos),
      // catch errors
      catchError(_ => 
        return of(null);
      )
    );
  
 
  ngOnInit() 
    this.produtoAutoComplete = this.vendaForm.valueChanges.pipe(
      startWith(''),
      // delay emits
      debounceTime(300),
      //map(options => options ? this.filter(options) : this.produtos.slice())      
      switchMap(value => 
        if (value !== '') 
          // lookup from github
          return this.lookup(value);
         else 
          // if no value is pressent, return null
          return of(null);
        
      )
    );
  

服务代码:

const API_URL = environment.apiUrl;

const httpOptions = 
  headers: new HttpHeaders( 'Content-Type': 'application/json' ), responseType: 'text' as 'json'
;


@Injectable(
  providedIn: 'root'
)
export class ProdutoService 
  private produtoUrl = API_URL + 'produto/';  // URL to web api
  dataChange: BehaviorSubject<Produto[]> = new BehaviorSubject<Produto[]>([]);
  // Temporarily stores data from dialogs
  dialogData: any;
  produtos: Produto[] = [];
  constructor(private httpClient: HttpClient)  

还有我的html

 <form class="example-form">
          <mat-form-field floatLabel="never">
            <input matInput type="text" aria-label="Number" matInput [formControl]="vendaForm" [matAutocomplete]="auto">

            <mat-placeholder class="placeholder">Search</mat-placeholder>

            <mat-autocomplete #auto="matAutocomplete">
              <mat-option *ngFor="let option of produtoAutoComplete | async" [value]="option.descProduto">
                option.descProduto
              </mat-option>
            </mat-autocomplete>
          </mat-form-field>
        </form>

我已经尝试了所有方法,遵循了数千个示例,但没有任何效果。就像我说的服务工作并返回我的 JSON,我的问题是当我尝试显示结果时。

【问题讨论】:

【参考方案1】:

经过很多小时后,我找到了解决这个问题的方法。

组件的TS:

export class VendaComponent implements OnInit 

  public vendaForm = new FormControl();
  vendas: Venda[] = [];
  results: any[];
  isLoading = false;

  constructor(private vendasService: VendaService, private produtoService: ProdutoService, private toastr: ToastrService)  

  ngOnInit() 
    this.vendaForm.valueChanges.subscribe(
      term => 
        if (term != '') 
          this.produtoService.search1(term).subscribe(
            data => 
              this.results = data as any[];
              console.log(data);
            )
        
      )
  

数据服务:

search1(term) 
    const params = new HttpParams()
      .set('descProduto', term)
      .set('codigoBarras', '123');//Hardcode parameter just for tests
      var listOfBooks= this.httpClient.get(this.produtoUrl + 'busca/',  params )
      .pipe(
        debounceTime(500),  // WAIT FOR 500 MILISECONDS ATER EACH KEY STROKE.
        map(
          (data: any) => 
            return (
              data.length != 0 ? data as any[] : [ "Produto": "No Record Found"  as any]
            );
          
        ));
    return listOfBooks;
  

显示材料自动完成的 HTML:

<form>
          <mat-form-field class="container">

            <!-- ADD AN INPUT BOX OF TYPE TEXT AND LINK IT TO THE AUTO COMPLETE PANEL. -->
            <input type="text" placeholder="Procure Produtos ..." matInput [formControl]="vendaForm" [matAutocomplete]="auto">

            <!-- CREATE AUTO COMPLETE PANEL WITH OPTIONS. -->
            <mat-autocomplete #auto="matAutocomplete">
              <mat-option *ngFor="let result of results" [value]="result.descProduto">
                 result.descProduto 
              </mat-option>
            </mat-autocomplete>

          </mat-form-field>
        </form>

希望对大家有所帮助。

【讨论】:

以上是关于Angular Mat AutoComplete 不显示/显示从后端返回的对象的下拉列表的主要内容,如果未能解决你的问题,请参考以下文章

mat-autoComplete 中的占位符不起作用,如 Angular Material Documentation 中所示

Angular Mat AutoComplete 不显示/显示从后端返回的对象的下拉列表

FormGroup CustomFilter 中的 Mat-AutoComplete

如何正确使用 mat-autocomplete 和远程 graphQL 数据?

使用 formArray 时出现 Mat-AutoComplete 错误

mat-autocomplete 过滤器以突出显示部分字符串匹配