简体   繁体   English

在组件中添加外部JS文件以使用Angular 2在浏览器中渲染图像

[英]Add external JS file in component to render images in browser with Angular 2

I make a site with Angular 2 and will add a JavaScript file to the component. 我使用Angular 2创建了一个网站,并将向该组件添加一个JavaScript文件。 This script must render the height of some images equal to the height of the window of the browser. 该脚本必须渲染某些图像的高度,使其等于浏览器窗口的高度。

How could I add this script to the component? 如何将该脚本添加到组件中?

The solutions I found on SO or anywhere else, looks like this: 我在SO或其他任何地方找到的解决方案如下所示:

import './home.component.js';

But it's not what I need! 但这不是我所需要的! I need this in my home.component.ts file: 我在home.component.ts文件中需要此文件:

@Component({
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss'],
    jsUrls: ['./home.component.js']
})

or something... 或者其他的东西...

Update 1: In my site I use Angular CLI and TypeScript. 更新1:在我的网站上,我使用Angular CLI和TypeScript。

Update 2: You could find my project on GitHub: https://github.com/WatchFriends/Web 更新2:您可以在GitHub上找到我的项目: https : //github.com/WatchFriends/Web

This works, and works well: 这行得通,而且效果很好:

In the angular-cli.json file, there is a section, "scripts". 在angular-cli.json文件中,有一个部分“脚本”。 Add the path to your script in that array (as a double-quoted string). 在该数组中将脚本路径添加为双引号字符串。

Here's a frag from that file: 这是该文件的片段:

  "mobile": false,
  "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.css",
    "../node_modules/font-awesome/css/font-awesome.css",
    "styles.css"
  ],
  "scripts": ["./app/my_script.js"],
  "environments": {
    "source": "environments/environment.ts",
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
  }

my_script is this: my_script是这样的:

function sayHello ( ) {
   console.log ( 'I am saying hello' );
}

Then just call it like you'd expect from anywhere. 然后,就可以随心所欲地调用它。 To beat the annoying "not found" error you may get in your IDE, you can either just do this: 要解决您可能在IDE中遇到的烦人的“未找到”错误,可以执行以下操作:

window [ 'sayHello' ] ( );

Or create a utility class that contains a reference to that function, such that you can import the class and call the function as usual (you are basically just providing a framework facade for your "my_script.js" functions). 或创建一个包含对该函数的引用的实用工具类,这样您就可以照常导入该类并调用该函数(您基本上只是为“ my_script.js”函数提供框架外观)。

I tried both, it worked just fine, no errors (you are using ng serve or ng build of course etc). 我都尝试了这两种方法,它都很好,没有错误(当然,您正在使用ng serve或ng build等)。

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

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