What is purpose of using forRoot in NgModule?

前端 未结 4 1409
花落未央
花落未央 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条回答
  •  猫巷女王i
    2021-01-31 15:03

    There are two ways to create a routing module:

    RouterModule.forRoot(routes)
    

    creates a routing module that includes the router directives, the route configuration and the router service

    RouterModule.forChild(routes)
    

    creates a routing module that includes the router directives, the route configuration but not the router service. The RouterModule.forChild() method is needed when your application has multiple routing modules.

    Remember that the router service takes care of synchronization between our application state and the browser URL. Instantiating multiple router services that interact with the same browser URL would lead to issues, so it is essential that there’s only one instance of the router service in our application, no matter how many routing modules we import in our application.

    When we import a routing module that is created using RouterModule.forRoot(), Angular will instantiate the router service. When we import a routing module that’s created using RouterModule.forChild(), Angular will not instantiate the router service.

    Therefore we can only use RouterModule.forRoot() once and use RouterModule.forChild() multiple times for additional routing modules.

提交回复
热议问题