Angular 2: “Global” lifecycle hooks?

后端 未结 1 575
我寻月下人不归
我寻月下人不归 2020-12-06 08:22

TL;DR

We are building an app with Angular 2 and would like to register a \"global\" ngOnInit and ngOnDestroy function. Wit

相关标签:
1条回答
  • 2020-12-06 08:45

    Forcing the behaviour for the entire app wouldn't be a good idea, this affects third-party components as well for starters.

    Boilerplate code can be moved into concrete base class. There are solutions for JS/TS multiple inheritance, e.g. @mixin, see also TypeScript guide.

    Since base class methods are fixed, class mixin can be expressed as a simplified decorator:

    class CustomLifecycle implements OnInit, OnDestroy  {
      constructor(
        public originalNgOnInit: Function,
        public originalNgOnDestroy: Function
      ) {}
    
      ngOnInit() {
        ...
        if (typeof this.originalNgOnInit === 'function') {
          this.originalNgOnInit();
        }
      }
    
      ngOnDestroy() {
        ...
        if (typeof this.originalNgOnDestroy === 'function') {
          this.originalNgOnDestroy ();
        }
      }
    }
    
    function Lifecycled() {
      return function (target: Function) {
        const customLifecycle = new CustomLifecycle(
          target.prototype.ngOnInit,
          target.prototype.ngOnDestroy
        );
    
        target.prototype.ngOnInit = customLifecycle.ngOnInit;
        target.prototype.ngOnDestroy = customLifecycle.ngOnDestroy;
      }
    }
    

    And it can be used like

    @Component({ ... })
    @Lifecycled()
    class SomeComponent { .... }
    

    The implementation is limited to ngOnInit, etc. prototype methods, arrow members require a constructor to be patched.

    0 讨论(0)
提交回复
热议问题