如何使用 angular 还原 ionic 4 中 ion-searchbar 过滤的数据?

How can I revert data filtered by ion-searchbar in ionic 4 with angular?

我正在尝试将 ionic 4 ion-searchbar ui 组件与 angular 一起使用。我可以使用以下组件过滤数据,但无法将过滤器还原为原始数据 我的组件看起来是这样的:

...
export class RepertorioPage implements OnInit {

  data: any;
  filtredData: any;

  constructor(private newsService: NewsService, private router: Router) { }

  ngOnInit() {
    this.newsService.getData('everything?q=bitcoin&from=2018-12-25&sortBy=publishedAt')
        .subscribe(data => {
        this.data = data
        this.filtredData = data
        })

  }

   ...

  getFiltredRepertorio(ev: any){

    let serVal = ev.target.value;
    if(serVal && serVal.trim() != ''){
      this.filtredData.articles = this.data.articles.filter((a) => {
        return (a.title.toLowerCase().indexOf(serVal.toLowerCase()) > -1);
      })
    }
  }

}

我的 html 是这样的:

...
<ion-content>
    <!-- List of Text Items -->
    <ion-searchbar showCancelButton cancelButtonText="Custom Cancel" (ionChange) = getFiltredRepertorio($event) id="searchText"></ion-searchbar>
    <ion-list>
      <ion-item (click)="getRepertorio(article)" *ngFor="let article of filtredData?.articles">
        <ion-label>{{article.title}}</ion-label>
      </ion-item>

    </ion-list>
</ion-content>

出了什么问题?我该如何解决?

尝试克隆数据而不是指向它的引用。 例如使用 lodash (import * as _ from 'lodash') with clone or cloneDeep

this.data = _.clone(data)
this.filtredData = data

编辑:

如果表单控件造成问题,我们可以用 ionChange 做同样的事情:

<ion-searchbar ... (ionChange)="doFilter($event)"></ion-searchbar>

doFilter 看起来像这样:

doFilter(val) {
  this.filteredData =  this.data.map(data => data.articles).map(options =>
    options.filter(option => 
       option.title.toLowerCase().indexOf(val.value.toLowerCase()) > -1)
    )
}

StackBlitz


原创:

我会将数据保存为 Observable 并使用异步管道和表单控件:

myControl = new FormControl();
filteredData: Observable<any[]>;
data: Observable<any[]>;

// ...

ngOnInit() {
  this.data = this.newsService.getData('...')

  this.filteredData = this.myControl.valueChanges
    .switchMap(value => this.filter(value))
}

filter(value: string): Observable<any[]> {
  return this.data.map(data => data.articles)
    .map(options => options
      .filter(option => option.title.toLowerCase().indexOf(value.toLowerCase()) > -1)
  )
}

然后是您设置异步管道并标记表单控件的模板,我们会监听和过滤这些更改:

<ion-content>
  <ion-searchbar ... [formControl]="myControl"></ion-searchbar>
  <ion-list>
    <ion-item ... *ngFor="let article of filteredData | async">
      <ion-label>{{article.title}}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>

这里是DEMO

请注意,不要使用 any,请输入您的数据 :)