我可以简化Angular的此方法吗?

时间:2018-09-14 08:51:58

标签: angular

我有这些变量:

 startLocations: Location[] = [];
  destLocations: Location[] = [];
  locationStartCtrl = new FormControl();
  locationDestCtrl = new FormControl();
  filteredStartLocations: Observable<Location[]>;
  filteredDestLocations: Observable<Location[]>;
  selectedStartLocation: Location;

我要简化此方法:

  private filterStartLocations() {
    this.filteredStartLocations = this.locationStartCtrl.valueChanges.pipe(
    startWith(''),
    map(location => location ? this._filterLocations(location, this.startLocations) : this.startLocations.slice())
    );
  }

 private filterDestLocations() {
    this.filteredDestLocations= this.locationDestCtrl.valueChanges.pipe(
      startWith(''),
      map(location => location ? this._filterLocations(location, this.destLocations ) : this.destLocations.slice())
    );
  }

我尝试过

  private filterDestLocations(getLocations: Location[], filterLocations: Observable<Location[]>, ctrl: FormControl) {
    filterLocations = ctrl.valueChanges.pipe(
    startWith(''),
    map(location => location ? this._filterLocations(location, getLocations) : getLocations.slice())
    );
    return filterLocations;
 }

但是,如果我尝试此操作,它将无法正常工作。这仅是因为filterLocations参数。有人知道吗?

2 个答案:

答案 0 :(得分:0)

尝试一下:

<Link to=“{pathname:’beerDetails’,state:{selectedbeer:selectedbeer}}/>

答案 1 :(得分:0)

一种简化的方法如下:

private filterLocations(locations: Location[], ctrl: FormControl, isDest: boolean = false): void {
    const fLocation: Observable<Location[]> = ctrl.valueChanges.pipe(
        startWith(''),
        map(location => location ? this._filterLocations(location, locations) : locations.slice();
    );

    if (!isDest) {
        this.filteredStartLocations = fLocation;
    } else {
        this.filteredDestLocations = fLocation;
    }
}

这是另一种方式:

private filterLocations(locations: Location[], ctrl: FormControl): void {
    return ctrl.valueChanges.pipe(
        startWith(''),
        map(location => location ? this._filterLocations(location, locations) : locations.slice();
    );
}

您将这样调用函数:

this.filteredStartLocations = this.filterLocations(...);