在使用Ionic 2中的NodeJS.Timer时找不到命名空间NodeJS。
在使用Ionic 2中的NodeJS.Timer时找不到命名空间NodeJS。
我正在尝试将我在https://github.com/bevacqua/dragula/issues/289#issuecomment-277143172找到的代码应用到我的Ionic项目中。
当我运行代码时,出现一个错误Cannot find namespace 'NodeJS'
,错误引用了touchTimeout: NodeJS.Timer;
这一行。
我该如何修改下面的代码以使NodeJS.Timer
这一行正常工作?
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({ selector: '[delayDragLift]' })
export class DelayDragLiftDirective {
dragDelay: number = 200; // 毫秒
draggable: boolean = false;
touchTimeout: NodeJS.Timer;
@HostListener('touchmove', ['$event'])
// @HostListener('mousemove', ['$event'])
onMove(e: Event) {
if (!this.draggable) {
e.stopPropagation();
clearTimeout(this.touchTimeout);
}
}
@HostListener('touchstart', ['$event'])
// @HostListener('mousedown', ['$event'])
onDown(e: Event) {
this.touchTimeout = setTimeout(() => {
this.draggable = true;
}, this.dragDelay);
}
@HostListener('touchend', ['$event'])
// @HostListener('mouseup', ['$event'])
onUp(e: Event) {
clearTimeout(this.touchTimeout);
this.draggable = false;
}
constructor(private el: ElementRef) {
}
}
问题的出现原因是在Ionic 2项目中使用NodeJS.Timer时找不到命名空间NodeJS。解决方法是将setTimeout和clearInterval更改为window.setTimeout和window.clearInterval。例如,将onDown方法更改为:
onDown(e: Event) { this.touchTimeout = window.setTimeout(() => { this.draggable = true; }, this.dragDelay); }
然后,声明部分更改为:
this.touchTimeout: number | undefined;
这样应该可以解决该问题,因为在针对浏览器的Angular项目中不应包含Node类型。
问题出现的原因是在Ionic 2中使用NodeJS.Timer时找不到NodeJS命名空间。解决方法是在src/tsconfig.app.json
文件中添加"node"
到"types"
数组中。如果src/tsconfig.app.json
文件不存在,则将指定部分添加到根文件夹的tsconfig.json
中。
代码示例:
{ "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/app", "baseUrl": "./", "module": "es2015", "types": [ "node" ] }, "exclude": [ "test.ts", "**/*.spec.ts" ] }