首页 > 解决方案 > Angular - 常见的 ngOnInit

问题描述

如果我在每个组件中都有

ngOnInit() {
  console.log('hello world');
}

如何避免在每个组件中编写该代码?我可以编写一些通用代码来为每个组件触发 onInit,也许在他们的模块中?或者在他们都使用的共享服务中,例如?

我对NavigationStartNavigationEnd有同样的问题。

谢谢

标签: angularboilerplatengoninit

解决方案


最简单的方法是从基础组件扩展:

@Component({
    selector: 'base-component',
    template: '',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class BaseComponent implements OnInit {

 ngOnInit (): void {
  console.log('hello world');
 }
}

extends BaseComponent在您的子组件中使用,例如:

@Component({
    selector: 'child-component',
    template: '',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent extends BaseComponent {
  // your logic
}

另一种方式:为每个组件使用本地提供者的服务:

@Injectable()
export class ActionService {
 constructor(){
   console.log('hello world');
 }
}

并将它 ( ) 注入providers: [ActionService]到必须具有此逻辑的组件中,每个组件将具有此服务的单独实例:

@Component({
    selector: 'main-page',
    templateUrl: './main-page.component.html',
    styleUrls: ['./main-page.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [ActionService]
})
export class MainPageComponent {}

至于我:第一个解决方案比每次都提供服务要好得多,但这取决于你:)


推荐阅读