You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2中外部JavaScript文件调用异常:myEObject未定义

Fixing "myEObject is not defined" Error in Angular 2 Component with External JS Files

Let's break down and fix the issues causing your "myEObject is not defined" error. There are two clear mistakes in your code leading to this problem, plus I'll share the corrected code to get everything working smoothly:

Identified Issues

  • Incorrect Template URL Extension: In external.component.ts, your templateUrl is set to ./external.component.htmll (note the extra 'l' at the end). This typo stops Angular from loading your component's template properly, which can disrupt component initialization and trigger unexpected errors.
  • Mismatched Function Name: Your external JS file myExternal.js defines a function named func1, but in your component's callFun() method, you're trying to call myEObject.myFunction()—these names don't align. This is a direct cause of the function call failure.

Corrected Code

external.component.ts

import { Component } from '@angular/core';
import '../myExternal.js';

declare var myEObject: any;

@Component({
  selector: 'external-file',
  templateUrl: './external.component.html' // Fixed the file extension
})
export class ExternalComponent {
  callFun(){
    myEObject.func1(); // Fixed the function name to match the JS file
  }
}

myExternal.js

var myEObject = (function() {
  return {
    func1: function() {
      document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
  }
})(myEObject||{})

external.component.html

<p id="demo">A Paragraph.</p> 
<button type="button" (click)="callFun()">Try it</button>

Quick Note

Double-check that the path to myExternal.js in your import statement matches your project's directory structure. The ../ in import '../myExternal.js' assumes the JS file is located one level above your component file—adjust this path if your file structure is different.

内容的提问来源于stack exchange,提问作者lpd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:28:52