在 Angular2 中包含外部(托管)javascript 文件 [英] Including external (hosted) javascript files in Angular2

查看:24
本文介绍了在 Angular2 中包含外部(托管)javascript 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过将记录添加到我的 angular-cli.json 文件来将外部 js 文件添加到我的 Angular2 项目中.

I'm trying to add an external js file into my Angular2 project by adding the record to my angular-cli.json file.

我已将一个文件添加到 [scripts] 数组中,如下所示:

I've added a file to the [scripts] array as below:

"scripts": ["https://as-identitydemo--c.na50.visual.force.com/resource/1495420277000/salesforce_login_widget_js"],

我读过的所有其他帖子都提到将这种格式用于本地托管或安装在 node_modules 等中的内容.

all the other posts that i've read refer to using this format for something that's either hosted locally, or installed in the node_modules etc..

如何包含外部 js 库并在我的项目中使用它?

How can I include an external js library and utilize that in my project?

推荐答案

你应该在你的 index.html 的 head 标签中导入库.其次,您必须使库对您的 Angular 项目可见.这意味着你需要打字.您可以搜索 https://github.com/DefinitelyTyped对于已经存在的类型或将类型添加到 Typings.d.ts 文件中.

You should import the library in your index.html in the head tag. Second you have to make the library visible to your Angular project. That means you need the typings. You can either search https://github.com/DefinitelyTyped for already existing types or add the types to the typings.d.ts file.

示例:

在您的页面中(在 Angular 应用程序之外),您可能有一个 javascript 全局变量:

In your page (outside of the Angular app) you might have a javascript global variable:

var testVar = 'testvalue';

然后在typings.d.ts中你可以通过添加使这个变量全局访问

Then in the typings.d.ts you can make this variable globally accessible by adding

declare var testVar:string;

然后你可以像这样在整个 Angular 项目中访问这个变量:

Then you can access this variable in the whole Angular project like that:

console.log(testVar);

您可以对外部库中的函数执行相同的操作.

The same you can do with functions in external libraries.

这是一个 Plunk 显示这一点(没有打字文件).希望这会有所帮助.

Here is a Plunk that shows that (without having a typings file). Hope this helps.

这篇关于在 Angular2 中包含外部(托管)javascript 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆