【问题标题】:Angular: Material Autocomplete is not working with post request?Angular:Material Autocomplete 不适用于发布请求?
【发布时间】:2021-09-01 04:51:55
【问题描述】:

我正在为我的项目使用 Angular 材料自动完成功能,但自动完成功能不起作用,我尝试了很多来找出问题所在,但目前我没有选择,

仅在浏览器控制台中显示 错误 response.filter is not a function。 我正在使用来自 JSON 格式数据的节点 API 的 post 请求获取数据

我正在尝试使用自动完成功能在搜索框中显示标题。

JSON 数据

 [{"Id": 1,
 "Title": "Pun",
 },
 {"Id": 2,
 "Title": "rocksold",
 },
 {"Id": 3,
 "Title": "Lehman",
 }]
 

app.service.ts

import { Injectable } from '@angular/core'; 
import { HttpClient} from '@angular/common/http';
import { AppSetting } from './appsetting'
import { Observable, of } from 'rxjs'; 
import { tap, map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class AppServiceService {
  private SERVERURL = AppSetting.API;
  constructor(private http: HttpClient) { }

  login(user){
    console.log(user);
    return this.http.post<any>(this.SERVERURL+"users",user);
  }
 

  opts = [];

  getData() {
    return this.opts.length ?
      of(this.opts) :
      this.http.post<any>('http://localhost:3000/articles/publicationData',{}).pipe(tap(data => this.opts = data))
  }

} 

app.component.ts

import { Component, OnInit, ElementRef  } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { AppServiceService } from './../app-service.service'; 
import { FormControl,FormBuilder, FormGroup } from '@angular/forms';
import { tap, startWith, debounceTime, distinctUntilChanged, switchMap, map } from 'rxjs/operators';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
 
 
@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})

export class MainComponent implements OnInit {

  myControl = new FormControl();
  options = [];
  filteredOptions: Observable<any[]>;

  constructor(private http: HttpClient,private auth : AppServiceService, private _router: Router, private formBuilder: FormBuilder){
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      debounceTime(400),
      distinctUntilChanged(),
      switchMap(val => {
            return this.filter(val || '')
       })
    )

}
  
    ngOnInit() {}

    filter(val: string): Observable<any[]> {
      // call the service which makes the http-request 
      return this.auth.getData()
       .pipe(
         map(response => response.filter(option => {
           return option.Title.toLowerCase().indexOf(val.toLowerCase()) === 0
         }))
       )
     } 

}

 

app.component.html

<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
 <mat-option *ngFor="let option of filteredOptions | async" [value]="option.Title">
                        {{option.Title}}
</mat-option>
</mat-autocomplete>
 </mat-form-field> 

【问题讨论】:

  • 你能不能打印地图里面的console.log(response)来检查你是否得到了正确的数据。
  • 我觉得你没有得到正确的数据也许它是对象而不是数组这就是你得到这个异常的原因[过滤器不是函数]我还看到你的 json 文件确保你包装了 while []中的数据作为数组
  • map(response =&gt; response.filter(option =&gt; {return option.Title.toLowerCase().indexOf(val.toLowerCase()) === 0 console.log(response); } )) )console.log 在地图中不起作用,请参阅
  • map( response => { console.log(response); return response.filter(option => {return option.Title.toLowerCase().indexOf(val.toLowerCase()) === 0 ; })

标签: angular autocomplete


【解决方案1】:

用 [] 包装你的 json 数据

[
 {"Id": 1,"Title": "Pun"},
 {"Id": 2,"Title": "rocksold"},
 {"Id": 3, "Title": "Lehman"}
]

【讨论】:

  • 如果您可以查看我的 API 调用,我认为调用 post API 肯定有问题
  • 你有teamViewer吗?直接检查代码
  • 谢谢你,艾哈迈德
【解决方案2】:

从自己的响应中检查问题后,响应结构是这样的

{
  results:[
   {item:1 ...},
   {item:2 ...},
   {item:2 ...},
 ]
}

这意味着您必须将过滤器方法中的地图更改为


filter(val: string): Observable<any[]> {
      // call the service which makes the http-request 
      return this.auth.getData()
       .pipe(
         map(response => response.results.filter(option => {
           return option.Title.toLowerCase().indexOf(val.toLowerCase()) === 0
         }))
       )
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2016-01-19
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    相关资源
    最近更新 更多