与用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';
现在程序应该可以正常运行了。