【问题标题】:angular input search field on an array of objects对象数组上的角度输入搜索字段
【发布时间】:2019-02-25 19:34:23
【问题描述】:

嘿,我是 Angular 新手,我有一个问题 我有一个对象数组:

holders: Holder[] = [
  { name: 'hanna', nationalId: 310, customerNumber: '123' },
  { name: 'jack', nationalId: 320, customerNumber: '124' },
  { name: 'sara', nationalId: 320, customerNumber: '125' },
];

在我的搜索字段中,我输入 customerNumber,如果持有人存在,其名称将显示在该字段下方,如果不存在,则会显示错误(持有人不存在) 组件:

constructor(private holderService: HolderService) {
   this.holderService.searchfunc(this.searchTerm$)
       .subscribe(results => {
           this.result = results;
       });
}
searchHolder(term: string): void {
   this.searchTerm$.next(term);
}

和服务:

searchfunc(terms: Observable<string>) {
   return terms.pipe(
       debounceTime(500),
       distinctUntilChanged(),
       map(term => this.searchEntries(term)));
}
searchEntries(term) {
   if(term){
       this.searchResult = this.holders.filter(x => x.customerNumber === term);
       if(this.searchResult[0]){
           return this.searchResult[0].name;
       }else{
           return 'the holder does not exist';
       }
   }else{
       this.search = term;
   }
}

有没有更好的解决方案?我想处理组件中而不是服务中持有人的存在

【问题讨论】:

    标签: angular search


    【解决方案1】:

    如果您愿意,您可以将整个内容放入组件中,但这样做是更好的方法。

    如果你想在组件中编写整个代码,你可以这样做。

    constructor(){
      this.searchTerm$.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        map(term => this.searchEntries(term))
        .subscribe(results => {
           this.result = results;
         });
      )
    }
    
    searchEntries(term){
        if(term){
            this.searchResult = this.holders.filter(x => x.customerNumber === term);
            if(this.searchResult[0]){
                return this.searchResult[0].name;
            }else{
                return 'the holder does not exist';
            }
        }else{
            this.search = term;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2015-12-17
      • 2017-08-17
      • 1970-01-01
      相关资源
      最近更新 更多