What is purpose of using forRoot in NgModule?

前端 未结 4 1404
花落未央
花落未央 2021-01-31 14:11

What is the purpose of using forRoot in NgModule?

Is it same as the providers in AngularJS 1.x?

How does it play the significant role in lazy loading?

TI

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 14:49

    forRoot() will be used to inject the providers at the top of the application. The instance of Component and directive are created a new instance everytime when they are invoked. When you mention the same at the root of the application (using forRoot()) only one instance will be created.

    Firstly, we need to understand that providers are injected with some difference than that components and directives are injected. When a class is annotated with @Injectable, only one instance of this class will be created upon call and is shared throughout the entire application. To do so, we have to add this(forRoot()) method when the class is imported in NgModule.

    Hope you are clear now.

提交回复
热议问题