我可以为每个组件添加一个进程吗?ngOnInit和OnDestroy?

时间:2017-11-13 09:33:46

标签: angular

我有一个可观察的,我需要在每个组件上绑定和删除。

是否可以在某处编写subscribe / unsubscribe逻辑并将其隐式包含在每个组件中?

就像创建/销毁组件的中间件一样

以下是我希望看到的示例: https://i.imgur.com/K8XtaFv.png

编辑:yurzui给了我使用super.ngOnInit()的想法 不像我想的那么干净,但是嘿 - 它有效。

import { Component, OnInit, OnDestroy } from '@angular/core';

export class ExtendHooks {
  ngOnDestroy() {
    console.log("Want this to fire first")
  }

  ngOnInit() {
    console.log('Want to fire first')
  }
}


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends ExtendHooks implements OnInit, OnDestroy {

  constructor(){
    super()
  }

  ngOnDestroy() {
    super.ngOnDestroy()
    console.log("Want this to fire second")
  }

  ngOnInit() {
    super.ngOnInit()
    console.log("Want to fire second")    
  }
}

1 个答案:

答案 0 :(得分:0)

尝试路由器生命周期挂钩navigationstart和navigationend