在Angular CLI应用程序中使用JavaScript全局库

与用JavaScript编写的AngularJS 1.x不同,Angular是使用TypeScript完全重写的。 将项目从AngularJS迁移到Angular时,您可能想知道如何在新框架中使用JavaScript全局库,例如jQuery。 在本文中,我将使用DWT(Dynamic Web TWAIN)JavaScript库作为示例来说明如何在Angular CLI应用程序中使用JavaScript全局库。

环境

@angular/cli: 1.0.3
node: 7.9.0
os: win32 x64
@angular/common: 4.1.2
@angular/compiler: 4.1.2
@angular/core: 4.1.2
@angular/forms: 4.1.2
@angular/http: 4.1.2
@angular/platform-browser: 4.1.2
@angular/platform-browser-dynamic: 4.1.2
@angular/router: 4.1.2
@angular/cli: 1.0.3
@angular/compiler-cli: 4.1.2

在Angular里使用Web TWAIN

安装Angular CLI:

npm install -g @angular/cli

初始化Angular项目:

ng new web-scan

这样会生成许多非必要文件。 要获得一个干净的项目,请参考https://github.com/angular/quickstart创建non-essential-files.txt

.git
.gitignore
.travis.yml
*.spec*.ts
bs-config.e2e.json
CHANGELOG.md
e2e
favicon.ico
karma.conf.js
karma-test-shim.js
LICENSE
non-essential-files.txt
non-essential-files.osx.txt
protractor.config.js
README.md

然后在Windows上使用以下命令删除这些文件:

for /f %i in (non-essential-files.txt) do del %i /F /S /QDelete non-essential files:
rd .git /s /q
rd e2e /s /q

安装Dynamic Web TWAIN JavaScript库 -  dynamsoft.webtwain.min.js:

npm install dwt --save

安装Dynamic Web TWAIN的TypeScript声明文件(.d.ts):

npm install @types/dwt --save

Dynamic Web TWAIN JavaScript库是一个像jQuery一样的全局库。 要包含该库,请打开.angular-cli.json并将库的路径添加到scripts:

"scripts": ["../node_modules/dwt/dist/dynamsoft.webtwain.min.js"],

或者,您可以把链接添加到src/index.html

<script type="text/javascript" src="http://www.dynamsoft.com/library/dwt/dynamsoft.webtwain.min.js"> </script>

编辑src/app/app.component.ts以添加扫描文档的功能:

export class AppComponent {
  title = 'Using Dynamic Web TWAIN in Angular Project';
 
  acquireImage(): void {
    const dwObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
    const bSelected = dwObject.SelectSource();
    if (bSelected) {
      const onAcquireImageSuccess = () => { dwObject.CloseSource(); };
      const onAcquireImageFailure = onAcquireImageSuccess;
      dwObject.OpenSource();
      dwObject.AcquireImage({}, onAcquireImageSuccess, onAcquireImageFailure);
    }
  }
}

将一个按钮和一个div元素添加到src/app/app.component.html

<button (click)="acquireImage()">Scan Document</button>
<div id="dwtcontrolContainer"></div>

现在, 尝试运行该应用程序:

ng serve --open

运行后,有一条错误消息:

找不到'Dynamsoft'。 如何解决这个问题? 我们可以使用'require'来获取引用吗?

显然,这不是正确的方法。 为了使编译器识别引用,我们可以使用三斜杠指令。 将/// <reference path="…" />/// <reference types="…" />添加到src/app/app.component.ts的顶部:

/// <reference types="dwt" />
 
import {Component} from '@angular/core';

现在程序应该可以正常运行了。

源代码

https://github.com/dynamsoft-dwt/angular-cli-application

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值