我在angular2中创建pdf文件时遇到了一点错误,我使用了jspdf和jspdf-autotable库。问题是我得到了数据 通过节点后端使用角度服务。我从后端收到的数据是json格式。所以jspdf-autotable插件可以处理它。
下面是我从后端获得的数据。
[{"notes":"gdsgdsgds","password":"04ba81ae04363cda785e3be93eb2e81d096d6465ec0c063d325cb48d2e1ef7511d28fd9194ae6d901ef1970d763754echXnvH8mlgzT5TK+ZdkzmEQ==","username":"gsdgdsg","folder":"dfgdf","name":"gdgfd","url":"https://www.npmjs.com/package/nodemailer"},{"notes":"test","password":"7e24572019254fecaf421fbea6a013282652ab3b43d03955292cb92b9ee011599179e4dcf7250332556a7aa38ce553fc1IWLrer/9XEr799GQ/aMPg==","username":"test","folder":"test","name":"test","url":"https://www.npmjs.com/package/nodemailer"}]
我在控制台中收到的错误显示如下。
The data should be an object or array, is: string
ERROR TypeError: inputData.forEach is not a function
at Object.createModels (eval at webpackJsonp.90.module.exports (addScript.js:9), <anonymous>:1220:15)
at Object.jsPDF.API.autoTable (eval at webpackJsonp.90.module.exports (addScript.js:9), <anonymous>:2277:15)
at SafeSubscriber._next (view-record.component.ts:92)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at CatchSubscriber.Subscriber._next (Subscriber.js:125)
at CatchSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
我使用此链接https://github.com/simonbengtsson/jsPDF-AutoTable
中的代码其他代码显示在下面
组件代码
exportRecords(type) {
this.recordService.exportRecords(type).subscribe(
(data) => {
var columns = [
{title: "Url", dataKey: "url"},
{title: "Name", dataKey: "name"},
{title: "folder", dataKey: "folder"}
{title: "username", dataKey: "username"},
{title: "Password", dataKey: "password"},
{title: "Notes", dataKey: "notes"}
];
var rows = data;
// Only pt supported (not mm or in)
var doc = new jsPDF('p', 'pt');
doc.autoTable(columns, rows);
doc.save('table.pdf');
}
},
}
服务代码
exportRecords(type) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var t = localStorage.getItem("tokenKey");
headers.append("Authorization", "Bearer " + t);
return this.http.get('/api/record/exportRecords', {headers: headers})
.map((res: Response) => res['_body'])
.catch((err: Response) => Observable.throw(err.json()));
}
路由器代码
router.get('/exportRecords', function(req, res, next) {
Record.find().lean().select({ "url": 1, "name": 1, "folder": 1, "username": 1, "password": 1, "notes": 1, "_id":0}).exec(function(err, records) {
if (err){
console.log('err:', err)
return res.status(400).json({errors: 'something is wrong'})
}
console.log('success:', records)
return res.status(200).json(records)
});
});
任何帮助都会被高峰化