Kevin Malone
Kevin Malone

Reputation: 109

Angular autocomplete searching with Observables

I'm trying to make an autocomplete using Observables but I'm getting an error that says

Property 'filter' does not exist on type 'Observable<Entity[]>'

How can I make an autocomplete based on what I made? (I was thinking of using .pipe() but I don't really understand it

Here is what I tried:

.ts

  entity$: Observable<Entity>;
  entities$: Observable<Entity[]>;

  inputEntity = new FormControl();
  autocompleteEntities: Entity[] = [];
  subEntityText: Subscription;

  constructor(
    private userProvider: UserProvider,
    private entityProvider: EntityProvider,
    private cd: ChangeDetectorRef
  ) {}

  ngOnInit() {
    this.userProvider.user$.subscribe((user: User) => {
      this.entities$ = this.entityProvider.getAll(user.uid); # GET ENTITIES BASED ON USER UID
    });

    this.subEntityText = this.inputEntity.valueChanges.subscribe((query: string) => {
      if (query === '') {
        this.entity$ = null;
      } else {
        this.autocompleteEntities = this.searchEntity(query);
        this.cd.detectChanges();
      }
    });
  }

  searchEntity(query: string): Entity[] {
    if (query === '') return [];

    const queryRegExp = new RegExp(query, 'i');

    return this.entities$
      .filter(char => queryRegExp.test(char.name))
      .sort((a, b) => a.name.length - b.name.length);
  }

.html

<input
  type="text"
  [formControl]="inputEntity"
  [matAutocomplete]="auto"
/>

<mat-autocomplete #auto="matAutocomplete" class="option-autocomplete" autoActiveFirstOption>
    <mat-option class="option" *ngFor="let entity of autocompleteEntities" [value]="entity">
        <div class="option-character">
          <span class="option-character-name">{{entity.name}}</span>
        </div>
    </mat-option>
</mat-autocomplete>

Thanks in advance

Upvotes: 0

Views: 1400

Answers (1)

Igor
Igor

Reputation: 62238

You need to return an observable, see also How do I return the response from an asynchronous call?.

You could use map operator to filter and sort the response. There are other options as well.

import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
searchEntity(query: string): Observable<Entity[]> {
    if (query === '') return of([]);

    const queryRegExp = new RegExp(query, 'i');

    return this.entities$
      .pipe(map((entities) => {
        return entities
            .filter(char => queryRegExp.test(char.name))
            .sort((a, b) => a.name.length - b.name.length)
      }));
  }

Upvotes: 1

Related Questions