L
L
Lancelot2021-10-18 13:57:54
Angular
Lancelot, 2021-10-18 13:57:54

How to do a search on rxjs?

Hello. And do not tell me, is it possible to somehow simplify the flow that causes the search on rxjs? The api may return null if it doesn't find an entry. Thank you.

export interface Organization {
  code: string,
  manager: string,
  fullName: string,
  name: string,
  address: string,
  activity: string,
  status: string
}

private subscription = new Subscription();

  constructor(private ufopService: UfopService) {
    this.subscription.add(
      this.searchText$.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap((code: string) => iif(
          () => code.length === MIN_SEARCH_LENGTH,
          this.ufopService.getOrganization(code).pipe(
            switchMap((value: Organization | null) => iif(
              () => value === null,
              of(''),
              of(value).pipe(
                pluck('fullName')
              ))
            )
          ),
          of(''))
        )
      ).subscribe(fullName => this.fullName = fullName)
    )
  }

  onKeyPress(event: Event) {
    const { value } = (event.target as HTMLInputElement);
    this.searchText$.next(value)
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2021-10-18
@Xuxicheta

fullName$ = formControl.valueChanges.pipe(
  switchMap((value: string) => this.ufopService.getOrganization(value)),
  map((organization:  Organization | null) => organization?.fullName ??  '')
)

inside getOrganization check for your length.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question