Angular AoT Custom Decorator在静态解析符号值时遇到错误

时间:2018-02-19 20:43:24

标签: angular typescript

我创建了一个装饰器来帮助我处理桌面/移动事件

import { HostListener } from '@angular/core';

type MobileAwareEventName =
  | 'clickstart'
  | 'clickmove'
  | 'clickend'
  | 'document:clickstart'
  | 'document:clickmove'
  | 'document:clickend'
  | 'window:clickstart'
  | 'window:clickmove'
  | 'window:clickend';

export const normalizeEventName = (eventName: string) => {
  return typeof document.ontouchstart !== 'undefined'
    ? eventName
        .replace('clickstart', 'touchstart')
        .replace('clickmove', 'touchmove')
        .replace('clickend', 'touchend')
    : eventName
        .replace('clickstart', 'mousedown')
        .replace('clickmove', 'mousemove')
        .replace('clickend', 'mouseup');
};

export const MobileAwareHostListener = (
  eventName: MobileAwareEventName,
  args?: string[],
) => {
  return HostListener(normalizeEventName(eventName), args);
};

问题是当我尝试使用--prod进行编译时,出现以下错误

typescript error
Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing
the function or lambda with a reference to an exported function (position 26:40 in the original .ts file),
resolving symbol MobileAwareHostListener in
.../event-listener.decorator.ts, resolving symbol HomePage in
.../home.ts

Error: The Angular AoT build failed. See the issues above

有什么问题?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:7)

这正是错误所说的。您正在执行此操作的位置不支持函数调用。 Angular内置装饰器isn't supported的行为的扩展。

AOT编译(由--prod选项触发)允许静态分析现有代码并用评估的预期结果替换一些部分。这些地方的动态行为意味着AOT不能用于应用程序,这是应用程序的主要缺点。

如果您需要自定义行为,则不应使用HostListener。由于它基本上在元素上设置了一个监听器,因此应该使用渲染器提供程序手动完成,这是优于DOM的Angular抽象。

这可以通过自定义装饰器来解决:

interface IMobileAwareDirective {
  injector: Injector;
  ngOnInit?: Function;
  ngOnDestroy?: Function;
}

export function MobileAwareListener(eventName) {
  return (classProto: IMobileAwareDirective, prop, decorator) => {
    if (!classProto['_maPatched']) {
      classProto['_maPatched'] = true;
      classProto['_maEventsMap'] = [...(classProto['_maEventsMap'] || [])];

      const ngOnInitUnpatched = classProto.ngOnInit;
      classProto.ngOnInit = function(this: IMobileAwareDirective) {
        const renderer2 = this.injector.get(Renderer2);
        const elementRef = this.injector.get(ElementRef);
        const eventNameRegex = /^(?:(window|document|body):|)(.+)/;

        for (const { eventName, listener } of classProto['_maEventsMap']) {
          // parse targets
          const [, eventTarget, eventTargetedName] = eventName.match(eventNameRegex);
          const unlisten = renderer2.listen(
            eventTarget || elementRef.nativeElement,
            eventTargetedName,
            listener.bind(this)
          );
          // save unlisten callbacks for ngOnDestroy
          // ...
        }

        if (ngOnInitUnpatched)
          return ngOnInitUnpatched.call(this);
      }
      // patch classProto.ngOnDestroy if it exists to remove a listener
      // ...
    }

    // eventName can be tampered here or later in patched ngOnInit
    classProto['_maEventsMap'].push({ eventName, listener:  classProto[prop] });
  }
}

并使用如下:

export class FooComponent {
  constructor(public injector: Injector) {}

  @MobileAwareListener('clickstart')
  bar(e) {
    console.log('bar', e);
  }

  @MobileAwareListener('body:clickstart')
  baz(e) {
    console.log('baz', e);
  }  
}

IMobileAwareDirective界面在这里发挥着重要作用。它强制类具有injector属性,这种方式可以访问其注入器和自己的依赖项(包括ElementRef,这是本地的,显然在根注入器上不可用)。此约定是装饰器与类实例依赖项交互的首选方法。还可以添加class ... implements IMobileAwareDirective以表达。

MobileAwareListenerHostListener的不同之处在于后者接受参数名称列表(包括魔法$event),而前者只接受事件对象并绑定到类实例。这可以在需要时更改。

这是a demo

此处还有一些问题需要解决。应在ngOnDestroy中删除事件侦听器。类继承可能存在潜在问题,需要另外测试。

答案 1 :(得分:1)

完整实施estus答案。这适用于继承。唯一的缺点是仍然需要组件在构造函数中包含injector

Full code on StackBlitz

import { ElementRef, Injector, Renderer2 } from '@angular/core';

function normalizeEventName(eventName: string) {
  return typeof document.ontouchstart !== 'undefined'
    ? eventName
        .replace('clickstart', 'touchstart')
        .replace('clickmove', 'touchmove')
        .replace('clickend', 'touchend')
    : eventName
        .replace('clickstart', 'mousedown')
        .replace('clickmove', 'mousemove')
        .replace('clickend', 'mouseup');
}


interface MobileAwareEventComponent {
  _macSubscribedEvents?: any[];
  injector: Injector;
  ngOnDestroy?: () => void;
  ngOnInit?: () => void;
}

export function MobileAwareHostListener(eventName: string) {
  return (classProto: MobileAwareEventComponent, prop: string) => {
    classProto._macSubscribedEvents = [];

    const ngOnInitUnmodified = classProto.ngOnInit;
    classProto.ngOnInit = function(this: MobileAwareEventComponent) {
      if (ngOnInitUnmodified) {
        ngOnInitUnmodified.call(this);
      }

      const renderer = this.injector.get(Renderer2) as Renderer2;
      const elementRef = this.injector.get(ElementRef) as ElementRef;

      const eventNameRegex = /^(?:(window|document|body):|)(.+)/;
      const [, eventTarget, eventTargetedName] = eventName.match(eventNameRegex);

      const unlisten = renderer.listen(
        eventTarget || elementRef.nativeElement,
        normalizeEventName(eventTargetedName),
        classProto[prop].bind(this),
      );

      classProto._macSubscribedEvents.push(unlisten);
    };

    const ngOnDestroyUnmodified = classProto.ngOnDestroy;
    classProto.ngOnDestroy = function(this: MobileAwareEventComponent) {
      if (ngOnDestroyUnmodified) {
        ngOnDestroyUnmodified.call(this);
      }

      classProto._macSubscribedEvents.forEach((unlisten) => unlisten());
    };
  };
}