我正在使用Material Angular开发一个表以显示Postgres数据库中的用户列表,而我正面临此问题:
要在表中显示结果,我正在从Spring Boot分页加载它们,因此URL类似于http://localhost:8080/user/page?_page=1&_pageSize=5&_sortDir=ASC
我已经在Angular中提供了从后端获取服务的服务,但是我收到的是“未定义”参数,而不是正确的参数。
我的 user-service.ts :
arr2 = [...arr1];
user.component.ts
const PATH = `${environment.url_base}/user`;
@Injectable({
providedIn: 'root'
})
export class UsersService implements IPaginationService<User> {
constructor(
private http: HttpClient
) {}
public getPage(pagRequest: PaginationDataRequest) :
Observable<PageData<User>> {
return this.http.get<PageData<User>>(PATH + '/page', {
params: pagRequest.toHttpParams()
});
}
IPaginationService
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
public formFilter: FormGroup;
public dataSource: DataSourceBase<User>;
public codIdUsuarioFilter: string[] = [];
public selectionUsuarios = new SelectionModel<string>(true, []);
public pageSizes = [15, 25, 50, 100];
private subscriptions: Subscription[] = [];
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
public columns = [
{columnDef: 'id', header: 'ID', cell: (row: User) => `${row.id}`, flex: 10, sortable: true},
{columnDef: 'name', header: 'Nombre', cell: (row: User) => row.name, sortable: true},
{columnDef: 'surname', header: 'Apellidos', cell: (row: User) => row.surname, sortable: true},
{columnDef: 'email', header: 'Email', cell: (row: User) => row.email, sortable: false},
{columnDef: 'incorporation_date', header: 'Incorporación', cell: (row: User) => row.incorporation_date, sortable: true}
];
public visibleColumns = ['id', 'name', 'surname', 'email', 'incorporation_date'];
public actions: RowActions<User>[] = [
{ icon: 'edit', action: (user: User) => {
this.router.navigateByUrl(`/user/${user.id}`);
}, color: 'primary'}
];
public buttonsHead: RowActions<any>[] = [];
constructor(private formBuilder: FormBuilder,
private route: ActivatedRoute,
private usersService: UsersService,
private router: Router,
private sessionService: SessionService)
{
this.dataSource = new UsersDataSource(usersService);
}
ngOnInit() {
this.formFilter = this.formBuilder.group({
id: ['', ],
name: ['', Validators.minLength(4)],
});
}
matcher = new MyErrorStateMatcher();
searchCodIdUsuario: string[] = [];
removeCodIdUsuario(codIdUsuarios: any): void {
const index = this.codIdUsuarioFilter.indexOf(codIdUsuarios);
if (index >= 0) {
this.codIdUsuarioFilter.splice(index, 1);
}
}
clean() {
this.formFilter.reset();
this.codIdUsuarioFilter = [];
this.refresh();
}
private validateForm() : boolean {
if(this.formFilter.get("name").invalid){
return false;
} else {
return true;
}
}
refresh() {
if (!this.validateForm()) {
return;
}
this.paginator.pageIndex = 0;
this.loadPage();
}
loadPage() {
this.formFilter.get('id').setValue(this.codIdUsuarioFilter);
let pagRequest = new PaginationDataRequest({
page: this.paginator.pageIndex + 1,
pageSize: this.paginator.pageSize,
sortFields: [this.sort.active || 'id'],
sortDir: this.sort.direction === 'desc' ? 'DESC' : 'ASC',
filter: this.formFilter.value
});
this.dataSource.loadPage(pagRequest);
}
ngAfterViewInit() {
this.preparePagedTable();
}
ngOnDestroy(): void {
this.subscriptions.forEach(sub => {
sub.unsubscribe();
});
}
private preparePagedTable() {
if (this.subscriptions.length === 0) {
// reset the paginator after sorting
let sub = this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
this.subscriptions.push(sub);
sub = merge(this.sort.sortChange, this.paginator.page).subscribe(() => this.loadPage());
this.subscriptions.push(sub);
sub = this.dataSource.requestReloadEvents.subscribe(() => this.refresh());
this.subscriptions.push(sub);
}
}
}
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
class UsersDataSource extends DataSourceBase<User> {
constructor(usersService: IPaginationService<User>) {
super(usersService);
}
}
我正在使用可恢复的MatTable,所以我只需要给它一些参数,例如dataSource等。事实是,当我加载表时,显示了列和分页,但是在装入GET请求时却失败了,因为在某种程度上,它接收到“未定义”。
错误
export type FilterObject = { [param: string]: string | string[]; };
export class PaginationDataRequest {
page: number;
pageSize: number;
sortFields: string[];
sortDir: 'ASC' | 'DESC';
filter?: FilterObject;
public toHttpParams() : HttpParams {
let params = new HttpParams({ fromObject: this.filter });
params = params.append("_page", `${this.page}`);
params = params.append("_pageSize", `${this.pageSize}`);
params = params.append("_sortDir", `${this.sortDir}`);
this.sortFields.forEach(fieldName => {
params = params.append("_sortFields", fieldName);
});
return params;
}
constructor(fields: Partial<PaginationDataRequest>) {
Object.assign(this, fields);
}
}
export class PageData<T> {
content: T[];
total: number;
constructor(content = [], total = 0) {
this.content = content;
this.total = total;
}
}
export interface IPaginationService<T> {
getPage(pagRequest: PaginationDataRequest) : Observable<PageData<T>>;
}