Angular 2+ - 在所有 ngOnInit 上自动运行相同的代码

The*_*Man 3 ngoninit angular

也许这个问题的答案也与 AngularJS (1.x) 相关,但我这里的问题是针对 Angular 2 及更高版本的。

我们知道,每个组件文件都有自己的 ngOnInit 函数,它会在组件初始化时运行其中的代码。在我当前的应用程序中,我需要在所有这些函数、所有组件中自动运行相同的代码段。现在,我只是为每个组件的 TS 文件复制这些函数之间的代码。有没有办法将这段代码一次性放在一个公共地方,并让所有这些 init 函数从那里自动运行它?这意味着,即使是添加到应用程序的全新组件也会运行此代码,作为其 init 函数的一部分......

Jen*_*ger 5

组件是类,因此可以扩展(抽象)基类,示例代码:

基类:

export abstract class AppBaseComponent implements OnInit {
constructor() { }
  ngOnInit() {
    // Your base code here
  }

}
Run Code Online (Sandbox Code Playgroud)

扩展类

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends AppBaseComponent implements OnInit {
  constructor() {
    super();
  }
  // Your component specific code here
}
Run Code Online (Sandbox Code Playgroud)

  • 除了扩展基类(如 Jens 的回答),您还可以使用面向方面的编程方法并使用打字稿定义自己的装饰器。查看本教程:https://www.meziantou.net/2018/01/11/aspect-oriented-programming-in-typescript (2认同)