首页 > 解决方案 > 无法从 TS 文件访问外部 JS 文件的功能

问题描述

我在外部 JS 文件中定义了一个函数。我无法在 home.page.ts 文件中使用它。它显示错误为 TypeError: Cannot read property 'functionName' of undefined

索引.html

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

多层来源.js

var multiLayerSource;

var layersHT = [];

function SetLayerHT(arglayersHT) {
    layersHT = arglayersHT;
}

主页.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.

请帮忙。

标签: javascriptnode.jsangulartypescriptionic-framework

解决方案


将您的 js 文件移动到资产文件夹,然后在您的代码中这样做

import 'assets/js/multiLayerSource';

declare var SetLayerHT: any;

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

推荐阅读