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, yourtemplateUrlis 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.jsdefines a function namedfunc1, but in your component'scallFun()method, you're trying to callmyEObject.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
相关产品推荐
相关产品推荐

