Я пытаюсь применить таблицу «Complete Example» с веб-сайта ng- bootstrap к моему собственному приложению angular. Единственное, что я пытаюсь сделать по-другому, - это использовать вызов веб-службы для получения данных вместо жесткого кодирования. По общему признанию, я немного борюсь с полным пониманием наблюдаемых, но я думаю, что происходит состояние гонки, поскольку мой код иногда возвращает данные в таблицу, а иногда нет, но никогда не показывает данные, если я добавляю сон в свой сервис code.
Оригинальный пример, на котором это основано, находится здесь https://stackblitz.com/run?file=app%2Ftable-complete.module.ts
Я думаю, что все сводится к конструктору файла service.ts, который
import {Injectable, PipeTransform, Input, OnInit} from '@angular/core';
import {BehaviorSubject, Observable, of, Subject} from 'rxjs';
import {DecimalPipe} from '@angular/common';
import {debounceTime, delay, switchMap, tap} from 'rxjs/operators';
import { IBatchPayment } from '@app/interfaces/ibatch-payment';
import { IBatchPaymentDetail } from '@app/interfaces/ibatch-payment-detail';
import { SortColumn, SortDirection } from '@app/utility/sortable.directive';
import { MyService } from './my.service';
interface SearchResult {
countries: IBatchPayment[];
total: number;
}
interface State {
page: number;
pageSize: number;
searchTerm: string;
sortColumn: SortColumn;
sortDirection: SortDirection;
}
const compare = (v1: string, v2: string) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0;
function sort(countries: IBatchPayment[], column: SortColumn, direction: string): IBatchPayment[] {
if (direction === '' || column === '') {
return countries;
} else {
return [...countries].sort((a, b) => {
const res = compare(`${a[column]}`, `${b[column]}`);
return direction === 'asc' ? res : -res;
});
}
}
function matches(country: IBatchPayment, term: string, pipe: PipeTransform) {
return country.jobId.toString().includes(term);
}
@Injectable({providedIn: 'root'})
export class BatchPaymentsService {
private batchPayments$: Observable<IBatchPayment[]>
private _loading$ = new BehaviorSubject<boolean>(true);
private _search$ = new Subject<void>();
private _countries$ = new BehaviorSubject<IBatchPayment[]>([]);
private _total$ = new BehaviorSubject<number>(0);
private COUNTRIES: IBatchPayment[] = [];
private _state: State = {
page: 1,
pageSize: 4,
searchTerm: '',
sortColumn: '',
sortDirection: ''
};
constructor(private pipe: DecimalPipe, private myService: MyService) {
this._search$.pipe(
tap(() => this._loading$.next(true)),
debounceTime(200),
switchMap(() => this._search()),
delay(200),
tap(() => this._loading$.next(false))
).subscribe(result => {
this._countries$.next(result.countries);
this._total$.next(result.total);
});
//THIS IS MY CALL TO GET THE DATA
this.myService.getBatchPayments('None').subscribe(
data => {
this.COUNTRIES = data;
},
error => {
}
);
this._search$.next();
}
get countries$() { return this._countries$.asObservable(); }
get total$() { return this._total$.asObservable(); }
get loading$() { return this._loading$.asObservable(); }
get page() { return this._state.page; }
get pageSize() { return this._state.pageSize; }
get searchTerm() { return this._state.searchTerm; }
set page(page: number) { this._set({page}); }
set pageSize(pageSize: number) { this._set({pageSize}); }
set searchTerm(searchTerm: string) { this._set({searchTerm}); }
set sortColumn(sortColumn: SortColumn) { this._set({sortColumn}); }
set sortDirection(sortDirection: SortDirection) { this._set({sortDirection}); }
private _set(patch: Partial<State>) {
Object.assign(this._state, patch);
this._search$.next();
}
private _search(): Observable<SearchResult> {
const {sortColumn, sortDirection, pageSize, page, searchTerm} = this._state;
// 1. sort
let countries = sort(this.COUNTRIES, sortColumn, sortDirection);
// 2. filter
countries = countries.filter(country => matches(country, searchTerm, this.pipe));
const total = countries.length;
// 3. paginate
countries = countries.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize);
return of({countries, total});
}
}