如果我在每个组件中
ngOnInit() {
console.log('hello world');
}如何避免在每个组件中编写该代码?我能写一些通用的代码来触发每个组件的onInit,也许在它们的模块中吗?或者是在他们共同使用的服务中,例如?
关于NavigationStart和NavigationEnd.,我也有同样的问题
Thx
发布于 2020-07-15 06:34:06
最简单的方法是从基本组件扩展:
@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 {}对我来说:第一个解决方案比每次提供服务要好得多,但这取决于您:)
发布于 2020-07-15 06:04:47
我建议您使用静态方法创建一个实用程序类。
假设每次初始化组件时都要打印hello world:
utility.ts:
class Utility {
static printHelloWorld() {
console.log("Hello world");
}
}在component.ts中:
首先,将实用程序类导入为:
import Utility from './path/to/utility/class';然后,在ngOnInit方法中:
ngOnInit() {
Utility.printHelloWorld();
}https://stackoverflow.com/questions/62908413
复制相似问题