【问题标题】:How to pass Observable data to PDF (pdfMake) in Ionic angular?如何以 Ionic 角度将 Observable 数据传递给 PDF (pdfMake)?
【发布时间】:2021-09-20 07:18:56
【问题描述】:

我正在使用 pdfMake 从可观察数据生成 PDF,但它在 PDF 中返回空或 [object Object]。 这是我的代码:

downloadPDF() {
  pdfMake.vfs = pdfFonts.pdfMake.vfs;

  var docDefination = {
    content: [
      {
        text: "lightHorizontalLines:",
        fontSize: 14,
        bold: true,
        margin: [0, 20, 0, 8],
      },
      {
        style: "tableExample",
        table: {
          headerRows: 1,
          body: [
            [{ text: "Details", style: "tableHeader" }],

            [{ text: this.observableData }], // observable to pdf data not showing here.
          ],
        },
        layout: "lightHorizontalLines",
      },
    ],
  };

  this.pdfObj = pdfMake.createPdf(docDefination);

  if (this.plt.is("cordova")) {
    this.pdfObj.getBase64(async (data) => {
      try {
        let path = `pdf/myletter_${Date.now()}.pdf`;

        const result = await Filesystem.writeFile({
          path,
          data: data,
          directory: FilesystemDirectory.Documents,
          recursive: true,
        });
        this.fileOpener.open(`${result.uri}`, "application/pdf");
      } catch (error) {
        console.log("Unable to write file: ", error);
      }
    });
  } else {
    this.pdfObj.download();
  }
}

注意:observableData 包含 firebase 文档值。

【问题讨论】:

  • 使用。 JSON.parse(this.observableData)
  • 'Observable' 类型的参数不可分配给'string'.ts(2345) 类型的参数我得到这个错误

标签: angular typescript cordova ionic-framework pdfmake


【解决方案1】:

要从 observable 获取数据,您需要订阅:

this.observableData.subscribe(data => this.realData = data);

realData 应该包含所需的数据(可能您应该另外以某种方式从 firebase 文档中提取它)。

您应该记住,subscribe 不会立即返回数据。您可以查看有关ObservablesSubscriptions 的文档:

https://rxjs.dev/guide/observable

https://rxjs.dev/guide/subscription

【讨论】:

  • 我已经尝试过这种方式,但它不起作用,它返回 [object Object]。虽然它显示在consol.log(realData) 但没有显示在 PDF 中。
  • @Ahmed 您可以从data 中提取您需要的内容并使用它。此外,您可以将整个对象表示为字符串:JSON.stringify(data)
  • 错误类型错误:将循环结构转换为 JSON --> 从带有构造函数“订阅者”的对象开始 |属性“_subscriptions”-> 带有构造函数“Array”的对象 |索引 0 -> 具有构造函数“SubjectSubscription”的对象 --- 属性“_parentOrParents”在 JSON.stringify () 处关闭了 JSON.stringify(data) 出现此错误
  • @Ahmed So... 检查控制台中data 对象的结构并提取所需的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 2017-07-30
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
相关资源
最近更新 更多