【问题标题】:Angular - Common ngOnInitAngular - 常见的 ngOnInit
【发布时间】:2020-11-04 13:41:54
【问题描述】:

如果我在每个组件中都有

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

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

我对 NavigationStartNavigationEnd 有同样的问题。

谢谢

【问题讨论】:

  • 您可以创建自定义装饰器,netbasal.com/…
  • 请提供更多信息,说明您的实际目标是什么。
  • 有什么关系?目标是避免样板。目标是通知用户组件已初始化。任何。然而,Dmitry Sobolevsky 给出了很好的答案。

标签: angular boilerplate ngoninit


【解决方案1】:

我建议你创建一个带有静态方法的实用程序类。

假设您想在每次初始化组件时打印 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();
}

【讨论】:

  • 这只是将每个组件中的一行替换为另一行。什么都解决不了。
【解决方案2】:

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

@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 {}

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

【讨论】:

  • 优秀的答案,清晰易懂。谢谢!
猜你喜欢
  • 2021-05-13
  • 2023-03-07
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2018-03-19
  • 2016-06-26
  • 2019-11-05
相关资源
最近更新 更多