我正在使用Angular版本5。我需要为angular-datatables做服务器端。它适用于POST请求,但无法使用GET请求进行。
有一个示例API(https://angular-datatables-demo-server.herokuapp.com/),它对GET和POST请求给出相同的响应。 Angular-datatables在服务器端执行POST,但不执行GET。
这是一个代码示例(https://stackblitz.com/edit/visible-columns-with-serverside-loading-angular-way)。
答案 0 :(得分:0)
最后使它正常工作。我需要通过请求参数发送数据表信息。这就是我所做的。
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参数和标头,而不是在正文中发送。
答案 1 :(得分:0)
这对我有用
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];
}
}
});
}
验证并调整了几件事,当存在服务器端参数时,我能够复制本机数据表参数的行为 Credit