简体   繁体   中英

How to finish angular observable before value changes check?

I am creating a search bar similar to Angular Autocomplete but I can't get my array in time.

import { Component, OnInit } from '@angular/core';
import { IngredientService } from '../ingredients-shared/ingredient-service.service';
import { Ingredient } from '../ingredients-models/ingredient';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
  selector: 'app-list-ingredients',
  templateUrl: './list-ingredients.component.html',
  styleUrls: ['./list-ingredients.component.css']
})
export class ListIngredientsComponent implements OnInit {

  options: string[] = ['Angular', 'React', 'Vue'];

  mylist: Ingredient[];


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


  constructor(public ingredientService: IngredientService) { }

    ngOnInit() {

    this.ingredientService.getAllIngredients().subscribe( (ingredients: Ingredient[]) => {
      this.mylist = ingredients
    });

    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(
        value => 
        this._filter(value))
    );
  }


  private _filter(value: string): Ingredient[] {

    console.log(value)
    const filterValue = value.toLowerCase();
    return this.mylist.filter(ingredient => ingredient.ingredient_name.toLowerCase().includes(filterValue));
  }

  displayIngredientName(subject: Ingredient){
    return subject ? subject.ingredient_name : undefined
  }

}

As you can see I need to populate mylist before checking for value changes in the form and I can't figure out how to finish beforehand.

I tried using async/await but I don't wanna use async in ngOnInit. I have also inserted the form changes inside the subscribe but of course that only happens once so it would not work.

Any advice? Thanks

Edit: This is the HTML:

    <form>
    <mat-form-field>
        <input type="text" matInput [matAutocomplete]="auto" [formControl]="myControl"/> 
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayIngredientName">
            <mat-option *ngFor="let ingredient of filteredList$ | async" [value]="ingredient" >
                {{ingredient.ingredient_name}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>
</form>

You need to combine both observables into single stream, since they depends on each other. User can start typing before data is loaded, with your approach search values entered before data is loaded will be ignored.

You could achieve it like this:

const ingredients$ = this.ingredientService.getAllIngredients();
const searchValues$ = this.myControl.valueChanges.pipe(startWith(''), map(val => val.toLowerCase()));
const filteredList$ = combineLatest(ingredients$, searchValues$)
                      .pipe(map(([list, searchVal]) => list.filter(item => item.ingredient_name.toLowerCase().includes(searchVal))));

Then just use async pipe in your template. And don't forget OnPush change detection. It is also good idea to use debounceTime, to limit search operations on fast typing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM