@PatriotSY

Как прервать выполнение запроса?

Использую ng-select, по примеру из доки (Демо, нижний пример), сделал поиск через бэкенд:

private loadCountry() {
        this.countryList$ = concat(
            of([]), // default items
            this.countryInput$.pipe(
                debounceTime(this.debounceTime),
                distinctUntilChanged(),
                tap(() => this.countryLoading = true),
                switchMap(search => {
                    return this.locationService.getCountry(search).pipe(
                        catchError(() => of([])),  // empty list on error
                        tap(() => this.countryLoading = false)
                    ).toPromise().then(data => {
                        const countries = [];
                        const cnt = data.body.length;
                        for (let i = 0; i < cnt; i++) {
                            countries.push(new Country(data.body[i]));
                        }
                        return countries;
                    });
                }),
            )
        );
    }


Но есть проблема: после того, как пользователь в селекте выберет нужный пункт, то этот метод сработает еще раз, но с search = null. Вот как этого избежать? Как правильно прервать выполнение этого метода при search = null?

Сделал так, но мне кажется, что это технически не верно, и есть более верные решения.

private loadCountry() {
        this.countryList$ = concat(
            of([]), // default items
            this.countryInput$.pipe(
                debounceTime(this.debounceTime),
                distinctUntilChanged(),
                tap(() => this.countryLoading = true),
                switchMap(search => {
                    
                    if (!search) {this.countryLoading = false; return []; }  // Мое решение
                    
                    return this.locationService.getCountry(search).pipe(
                        catchError(() => of([])), // empty list on error
                        tap(() => this.countryLoading = false)
                    ).toPromise().then(data => {
                        const countries = [];
                        const cnt = data.body.length;
                        for (let i = 0; i < cnt; i++) {
                            countries.push(new Country(data.body[i]));
                        }
                        return countries;
                    });
                }),
            )
        );
    }
  • Вопрос задан
  • 451 просмотр
Решения вопроса 1
mtix
@mtix
Front-end developer
В pipe заюзай оператор filter rxjs и отфильтруй значения с null.

https://www.learnrxjs.io/operators/filtering/filte...
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Xuxicheta
@Xuxicheta Куратор тега Angular
инженер
А в примере входной параметр [minTermLength]="2" вам ни о чем не говорит?
и уберите промис, кошмар же
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы