我正在尝试创建一个PDF,其中数据来自数据库。以下是我在TypeScript中执行变量声明的方法。
essay = {
"title": "",
"author": { "fullname": "" },
"intro": "",
"conclusion": "",
"paragraphs": [ { "paragraph": "" } ]
}
正如您在此处所见,这些段落是数组类型。因此,当触发生成PDF的按钮时,将调用以下函数。
CreatePdf(){
var docDefinition = {
content: [
{ text: this.essay.title, style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
{ text: 'Written By : '+this.essay.author.fullname, style: 'subheader' },
{ text: this.essay.intro, style: 'story', margin: [0, 20, 0, 20] },
// Foreach essay.paragraphs and display the value
{ text: this.essay.conclusion, style: 'story', margin: [0, 20, 0, 20] }
]
}
this.pdfObj = pdfMake.createPdf(docDefinition);
this.pdfObj.download();
}
问题是,我如何做foreach以显示content:[]
中的所有段落值?我正在尝试在内容中应用以下循环但不能这样做。
for(let parag of this.essay.paragraphs){
console.log(parag.paragraph);
};
答案 0 :(得分:1)
您可以使用...
运算符和map()
:
CreatePdf(){
var docDefinition = {
content: [
{ text: this.essay.title, style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
{ text: 'Written By : '+this.essay.author.fullname, style: 'subheader' },
{ text: this.essay.intro, style: 'story', margin: [0, 20, 0, 20] },
...this.essasy.paragraphs.map( p => {
return {text: p.paragraph, style: 'story', margin: [0, 20, 0, 20]};
}),
{ text: this.essay.conclusion, style: 'story', margin: [0, 20, 0, 20] }
]
}
this.pdfObj = pdfMake.createPdf(docDefinition);
this.pdfObj.download();
}
map()
顾名思义建议使用给定的函数映射每个元素,...
只是展平数组。