无法从另一个.ts文件

时间:2017-04-04 16:04:32

标签: javascript angular typescript

我很感激你2美分来解决调用另一个文件中定义的函数的问题。我阅读了Typescript的文档,建议设置一个接口或模块,然后引用它,但我收到的错误如下所示。

错误

ReferenceError: viewReport is not defined

文件结构

sample
  - sample.component.ts
  - sample.component.html
  - sample.component.css
  pdf
    viewReport.ts

sample.component.ts

import './pdf/viewReport';

declare var pdfMake: any;
declare var viewReport: any;

export class SampleComponent {

    addr = {
        "streetaddress": '',
        "cityName": '',
        "stateCode": '',
        "zipCode": ''
    };

    constructor() {}

    data = {
        header: {
            "address": {
                "street": this.addr.streetAddress,
                "city": this.addr.cityName,
                "state": this.addr.stateCode,
                "zip": this.addr.zipCode 
            }
        }

    }

    downloadPdf(){
        let pdf = pdfMake;
        pdf.createPdf(viewReport(this.data)).download('test.pdf');
    }
}

viewReport.ts

function viewReport( data ) {
    let docDefinition = {
      content: [{
        text: 'Address: ' + data.header.address.street
      }]
    }
    console.log( 'data:: ', data );
    return docDefinition;
}

1 个答案:

答案 0 :(得分:0)

我能够通过对代码进行以下更改来解决此问题:

<强> viewReport.ts

导出

时添加关键字“默认
export default function viewReport( data ) {

<强> sample.component.ts

替换

import './pdf/viewReport';
declare var viewReport: any;

import viewReport from './pdf/viewReport';

<强>参考

@n00dl3
@vesse
https://www.typescriptlang.org/docs/handbook/modules.html