e:TouchEvent的@HostListener导致Firefox崩溃,并显示“ ReferenceError:未定义TouchEvent”。

时间:2018-07-01 14:35:02

标签: angular firefox touch-event

使用@HostListener和显式键入为TouchEvent的事件参数会导致Firefox崩溃并显示以下错误消息:

  

ReferenceError:未定义TouchEvent。

一个例子:

@HostListener('touchstart', ['$event']) // or 'touchend', 'touchmove'
onTouchStart(e: TouchEvent): void {}

我可以想出几种方法来防止自己发生这种情况:

  • 使用e: TouchEvent | anye: any(或完全不指定类型)
  • 使用elRef.nativeElement.addEventListener('touchstart', (e: TouchEvent) => {})
  • 使用Observable.fromEvent(elRef.nativeElement, 'touchstart').subscribe((e: TouchEvent) => {})

但是使用any| any似乎是一种技巧,而其他两个选项则无法利用该框架。 是否有另一种更好,更安全的方式来解决此问题,如果没有,哪种方法更可取?

(也许有人也可以解释Angular实际在做什么,以及为什么仅在将事件显式键入为TouchEvent时才发生此错误的原因)


编辑:Angular 7中仍然存在该问题。 编辑:此问题显然已在Angular 6中解决。

2 个答案:

答案 0 :(得分:1)

当方法上有装饰器时,打字稿编译器会将参数的类型存储在元数据中,由于未在其中定义TouchEvent,因此在桌面Firefox中失败。可以通过用存根填充缺少的类型来解决。只需将以下代码添加到polyfills.ts

for (const type of ['TouchEvent']) {
    if (typeof window[type] === 'undefined') {
        window[type] = function () { };
    }
}

要填充其他类型,请将它们添加到列表中。一句警告-这可能会破坏通过检测window.TouchEvent来检查是否存在触摸事件的代码。

无论如何,问题似乎只发生在JIT编译器上,因此它可能会在常春藤中消失。

答案 1 :(得分:0)

您可以告诉Angular不要在tsconfig.json中发出装饰器元数据: "emitDecoratorMetadata": false