最简单的方法是从基础组件扩展:
@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 {}
就我而言:第一个解决方案比每次都提供服务要好得多,但这取决于你:)