简体   繁体   English

如何在 Angular 中包含外部 javascript 文件?

[英]How to include external javascript files in Angular?

I've been messing around in Angular and I am trying to include an external .js file but Angular keeps ignoring it.我一直在使用 Angular,我试图包含一个外部 .js 文件,但 Angular 一直忽略它。 I tried including the file in the <header> .我尝试将文件包含在<header>

I tried including it by using the styleUrl inside the component我尝试通过在组件内使用 styleUrl 来包含它

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  stylesUrl: ['/js/bootstrap.min.js']
})

but nothing seems to work.但似乎没有任何效果。

How should I been doing this?我应该怎么做?

Add a script tag to your index.html file (or equivalent) and set the src as the JavaScript file.script标记添加到您的index.html文件(或等效文件)并将 src 设置为 JavaScript 文件。 Then when the page is requested it will have the file included.然后当页面被请求时,它将包含文件。 If you need to call specific bootstrap methods you will want to import the library inside your component using module imports to reference it inside your TypeScript code.如果您需要调用特定的引导程序方法,您将需要使用模块导入在您的组件中导入库以在您的 TypeScript 代码中引用它。

Your question is specific to Angular 2 and stylesUrl is for css not js.您的问题是针对 Angular 2 的,stylesUrl 是针对 css 而不是 js。

Wiring up dependencies in Angular 2 is done in different ways depending on what the dependency is.在 Angular 2 中连接依赖项以不同的方式完成,具体取决于依赖项是什么。 Dependencies can be wired by extending a class, injecting a dependency, or adding an annotation in nice cases.可以通过扩展类、注入依赖项或在合适的情况下添加注释来连接依赖项。 In non-nice cases hacks may be required.在不太好的情况下,可能需要进行黑客攻击。 Here is the official documentation on dependency injection .这是关于依赖注入的官方文档

It looks like you care about Bootstrap in particular.看起来您特别关心 Bootstrap。 Here is how you can inject Bootstrap into an ng2 component .以下是将 Bootstrap 注入 ng2 组件的方法

On styleUrl, you should include the style files.在 styleUrl 上,您应该包含样式文件。 And you can include the external javascript or css files on angular.json (from Angular 6+) or angular-cli.json (before Angular 6).您可以在 angular.json(来自 Angular 6+)或 angular-cli.json(Angular 6 之前)上包含外部 javascript 或 css 文件。

Or simply, you can include those on index.html.或者简单地说,您可以将那些包含在 index.html 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM