无法从TS文件访问外部JS文件的功能

时间:2019-09-10 07:51:21

标签: javascript node.js angular typescript ionic-framework

我已经在外部JS文件中定义了一个函数。我无法在home.page.ts文件中使用它。它显示为TypeError错误:无法读取未定义的属性'functionName'

index.html

<body>
    <app-root></app-root>
    <script src="assets/multiLayerSource.js"></script>
</body>

multiLayerSource.js

var multiLayerSource;

var layersHT = [];

function SetLayerHT(arglayersHT) {
    layersHT = arglayersHT;
}

home.page.ts

import { Component } from '@angular/core';
import { OnInit, Renderer, ViewChild  } from '@angular/core';
declare var multiLayerSource: any;

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
    layersHTP: any = [];
    constructor() {}

    ngOnInit() {
        this.layersHTP.push( 'a', 'b', 'c', 'd' );
        multiLayerSource.SetLayerHT(this.layersHTP);
    }
}

尝试访问SetLayerHT()时显示错误。 错误是:

TypeError: Cannot read property 'SetLayerHT' of undefined.

请帮助。

1 个答案:

答案 0 :(得分:2)

将您的js文件移至资产文件夹,然后在代码中执行以下操作

import 'assets/js/multiLayerSource';

declare var SetLayerHT: any;

ngOnInit() {
 this.layersHTP.push( 'a', 'b', 'c', 'd' );
 SetLayerHT(this.layersHTP);
}