【问题标题】:Fixed: Angular 9: Undecorated base classes that use Angular features已修复:Angular 9:使用 Angular 功能的未修饰基类
【发布时间】:2020-02-17 06:39:14
【问题描述】:

我最近更新到 Angular v9,根据更改日志中的定义,不推荐使用使用 Angular 功能或由指令或组件扩展的未修饰基类。

所以我的应用程序中有很多 mixin,如下所示:

销毁:

export const Destroy = <T extends Constructor>(base: T = class {} as T) =>
  class extends base implements OnDestroy {
    destroy$ = new Subject<boolean>();

    ngOnDestroy(): void {
      this.destroy$.next(true);
      this.destroy$.complete();
    }
  };

滚动:

export const Scroll = <T extends Constructor>(base: T = class {
} as T) =>
  class extends base {
    public scrollToFirstError(form: FormGroup, scrollSelector?: string) {
      form.markAllAsTouched();
      const target = jQuery('.ng-invalid:not("form")').first();
      const scrollContainer = jQuery(scrollSelector || 'html,body');
      const subHeaderHeight = scrollSelector ? 0 : Number.parseInt(getComputedStyle(document.documentElement)
        .getPropertyValue('--height').trim(), 10);
      scrollContainer.animate(
        { scrollTop: jQuery(target).offset().top - jQuery(scrollContainer).offset().top - subHeaderHeight - 50 }, 'slow');
      target.focus();
    }
  };

在我的组件中扩展它,例如,

export class ComponentA extends Destroy(Scroll)

并尝试访问这些 mixin 的属性会引发以下错误:

this.apiService.getData().pipe(takeUntil(this.destroy$)... // Property 'destroy$' does not exist on type 'ComponentA'.


this.scrollToFirstError(this.form, '.modal'); // Property 'scrollToFirstError' does not exist on type 'ComponentA'.

谁能帮我提出解决问题的建议?提前致谢!

********* 更新 *********

在我的组件中:

export const MixinedClasses: any = Destroy(Scroll());

  @Component({
  selector: 'app-loan-list',
  templateUrl: './loan-list.component.html',
  styleUrls: ['./loan-list.component.scss']
})
export class Component extends MixinedClasses {}

【问题讨论】:

    标签: angular typescript mixins angular9


    【解决方案1】:

    只需将DestroyScroll 转换为@component 装饰组件,它应该可以正常工作。

    添加:

    // Destroy const becomes a decorated class
      @Component({
      selector: 'app-destroy'
    })
    export class Destroy implements OnDestroy{}
    
    // Scroll const becomes a decorated class
      @Component({
      selector: 'app-scroll'
    })
    export class Scroll{}
    

    这只是一个想法,您必须使其适合您的特定实施。

    老实说,我并没有完全遵循您通过将 base 作为参数传入来扩展它们的方式,因此您可能需要使用标准类重新考虑整个方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 2020-05-23
      • 2021-07-02
      • 2021-07-07
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多