У меня есть данные, поступающие в компонент моего приложения Angular через сетевой запрос.Это observable
и выглядит так:
this.streamFiltersService.getByFilters(
this.page - 1, this.pagesize, this.currentStage, this.language = filters['language'], this.location = filters['location'],
this.zipcode = filters['zip'], this.firstName = filters['firstName'], this.lastName = filters['lastName'],
this.branch = filters['branch'], fn);
Здесь есть обратный вызов fn
, который выглядит так:
let fn = resRecordsData => {
this.records = resRecordsData;
};
Проблема, с которой я работаюДело в том, что по мере того, как многочисленные компоненты фильтра входят в компонент, я получаю несколько сетевых запросов - и для пользователя данные экрана меняются несколько раз.Кроме того, поскольку это асинхронно, иногда один из первых запросов возвращается последним, и фильтры не применяются на экране, который видит пользователь.
Полная функция выглядит следующим образом:
public onFilterReceived(values)
{
let filters = {};
if (values) {
filters = values;
}
this.route.params.subscribe(
(params: any) => {
this.page = params['page'];
}
);
console.log('onFilterReceived() firing...');
let fn = resRecordsData => {
this.records = resRecordsData;
};
this.streamFiltersService.getByFilters(
this.page - 1, this.pagesize, this.currentStage, this.language = filters['language'], this.location = filters['location'],
this.zipcode = filters['zip'], this.firstName = filters['firstName'], this.lastName = filters['lastName'],
this.branch = filters['branch'], fn);
}
Как продолжение, когда я добавляю console.log
к обратному вызову в onFilterReceived()
, вот так:
let fn = async resRecordsData => {
console.log('records: ', resRecordsData);
this.records = await resRecordsData;
};
Что выводит на консоль так:
records: {ok: true, status: 200, statusText: "OK", data: Array(1), count: 1}
records: {ok: true, status: 200, statusText: "OK", data: Array(12), count: 115}
records: {ok: true, status: 200, statusText: "OK", data: Array(1), count: 1}
records: {ok: true, status: 200, statusText: "OK", data: Array(1), count: 1}
records: {ok: true, status: 200, statusText: "OK", data: Array(1), count: 1}
records: {ok: true, status: 200, statusText: "OK", data: Array(12), count: 115}
records: {ok: true, status: 200, statusText: "OK", data: Array(12), count: 115}
records: {ok: true, status: 200, statusText: "OK", data: Array(12), count: 115}
records: {ok: true, status: 200, statusText: "OK", data: Array(12), count: 115}
records: {ok: true, status: 200, statusText: "OK", data: Array(12), count: 115}
Обратите внимание, что, поскольку я применил фильтр, правильным значением является Массив (1).Как видите, поскольку эти вызовы асинхронны, они возвращаются не в порядке.В идеале мне нужен один вызов, который приводит к следующему:
records: {ok: true, status: 200, statusText: "OK", data: Array(1), count: 1}
Основываясь на предложении ниже, я попытался объединить предложенные операторы в обратный вызов onFilterReceived()
, например:
public async onFilterReceived(values)
{
let filters = {};
if (values) {
filters = values;
}
this.route.params.subscribe(
(params: any) => {
this.page = params['page'];
}
);
console.log('onFilterReceived() firing...');
let fn = async resRecordsData => {
await resRecordsData
.distinctUntilChanged()
.debounceTime(1000)
.switchMap( resRecordsData => {
this.records = resRecordsData;
});
console.log('records: ', this.records);
};
this.streamFiltersService.getByFilters(
this.page - 1, this.pagesize, this.currentStage, this.language = filters['language'], this.location = filters['location'],
this.zipcode = filters['zip'], this.firstName = filters['firstName'], this.lastName = filters['lastName'],
this.branch = filters['branch'], fn);
}
... но я получаю сообщение об ошибке:
error_handler.js: 60 Ошибка: Uncaught (в обещании): TypeError: resRecordsData.distinctUntilChanged не является функцией