我使用的是Angular版本5,我需要为angular-datatables做服务器端的工作。它可以处理POST请求,但我不能处理GET请求。
有一个示例接口(https://angular-datatables-demo-server.herokuapp.com/),它对GET和POST请求给出相同的响应。Angular-datatables在服务器端执行POST,但不执行GET。
下面是一个代码示例(https://stackblitz.com/edit/visible-columns-with-serverside-loading-angular-way)。
发布于 2019-01-15 14:56:49
终于让它工作了。我需要通过请求参数发送数据表信息。这是我所做的。
this.dtOptions = {
paging: true,
lengthChange: false,
searching: true,
pageLength: 10,
columnDefs: [{ targets: 3, orderable: false }],
pagingType: 'simple_numbers',
order: [[0, 'desc']],
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
const params = this.objectToHttpParams(dataTablesParameters);
console.log('params', params);
this.http
.get(
'http://myapi.com',
{
params: params,
headers: new HttpHeaders().set(
'token',
localStorage.getItem('token')
)
}
)
.subscribe(resp => {
this.result = resp['data'];
callback({
recordsTotal: resp['length'],
recordsFiltered: resp['length'],
data: []
});
});
}
};
// Helper Function
objectToHttpParams(obj: any) {
return Object.entries(obj || {}).reduce((params, [key, value]) => {
return params.set(
key,
isObjectLike(value) ? JSON.stringify(value) : String(value)
);
}, new HttpParams());
}有了这些选项,我就能够使它与GET请求一起工作,还可以发送HTTP参数和头部,而不是在主体中发送。
发布于 2021-04-07 00:22:42
这对我很有效
Example reference
ajax: (dataTablesParameters: any, callback) => {
const params = {};
this.objectToHttpParams(params , dataTablesParameters , '');
this.http
.get(
'http://myapi.com,
{
params: params,
headers: new HttpHeaders().set(
'token',
localStorage.getItem('token')
)
}
).subscribe(resp => {
this.result = resp['data'];
callback({
recordsTotal: resp['length'],
recordsFiltered: resp['length'],
data: []
});
});
},
objectToHttpParams(params: any, data: any, currentPath: string) {
Object.keys(data).forEach(key => {
if (data[key] instanceof Object) {
if (currentPath !== '' ) {
this.objectToHttpParams(params, data[key], `${currentPath}[${key}]`);
} else {
this.objectToHttpParams(params, data[key], `${currentPath}${key}`);
}
} else {
if (currentPath !== '' ) {
params[`${currentPath}[${key}]`] = data[key];
} else {
params[`${currentPath}${key}`] = data[key];
}
}
});
}经过验证和调整,我能够在服务器端参数存在时复制原生datatable参数的行为Credit
https://stackoverflow.com/questions/54144542
复制相似问题