【问题标题】:Angular 2 load data once and filter Observable locallyAngular 2 加载一次数据并在本地过滤 Observable
【发布时间】:2017-04-05 18:41:52
【问题描述】:

我有一个 Angular 2 应用程序,并且我设法在我的页面上设置了一个输入,该输入带有一个调用 api 并执行服务器端过滤和返回值的自动完成功能。很像这里的教程。

现在,我正在尝试向我的页面添加更多输入,但我不需要在服务器端过滤这些输入。那将是低效的。最好在我的组件加载时获取所有值,然后在组件中进行过滤。这给我带来了很多问题。我有一个 api 调用,它返回我需要的 3 个字符串数组。我使用标准方法从 Angular 服务中获取这些:

getFormFilters(): Observable<FormFilterModel> {
    return this._http.get(this.baseUrl+this.getFormFiltersPath)
      .map(res => res.json() as FormFilterModel);
  }

型号:

export interface FormFilterModel {
    array1: string[];
    array2: string[];
    array3: string[];
}

这很好,我得到了我的 observable。我卡住的地方是我现在如何在本地过滤这 3 个数组?我将输入连接到我的表单控件,就像我使用服务器端过滤输入一样。我不知道如何获取 Observable 中的实际数组来过滤它们。这是我使用该代码的地方:

this.filteredArray1$ = this.searchForm.controls.array1Search.valueChanges
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(term => //some filtering here of formFilterModel$ to return a subset of array1 based on input)

我可以通过 RegExp 过滤一个数组,但是在 observable 中获取实际数组是我似乎无法做到的。

【问题讨论】:

标签: javascript angular typescript rxjs angular2-observables


【解决方案1】:

订阅您的 api 调用并将结果存储在组件中。然后,过滤valuesChanges.map中的数组。

ngOnInit() {
  this.getFormFilters().subscribe(formFilters => {
    this.formFilters = formFilters;
  });

  this.filteredArray1$ =  this.searchForm.controls.array1Search.valueChanges
    .debounceTime(300)
    .distinctUntilChanged()
    .map(search => this.formFilters.array1.filter(value => matches(value, search)))
}

【讨论】:

    【解决方案2】:

    首先您必须订阅响应,然后过滤接收到的对象。

     formfilterData :FormfilterModel;
     filteredArray1:stringp[]=[];
     this.serviceOb.getFormFilters().subscribe((formfilterData)=>{
        this.formfilterData=formfilterData;
    
    
      });
       this.formfilterData.array1.filter((data)=>{
    
        this.formfilterData.push(data);
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2019-11-01
      相关资源
      最近更新 更多