Angular:forRoot/forChild 方法的用法? [英] Angular: forRoot/forChild methods usage?

查看:21
本文介绍了Angular:forRoot/forChild 方法的用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶没有确切的答案:

forRoot/forChild 方法的用途是什么?

What are methods forRoot/forChild made for?

例如在 RouterModule 中:

For example in RouterModule:

Router.forRoot(routes)

推荐答案

RouterModule#forRoot

创建一个包含所有路由器提供程序和指令的模块.它也是可选地设置应用程序侦听器以执行初始导航.

Creates a module with all the router providers and directives. It also optionally sets up an application listener to perform an initial navigation.

虽然 RouterModule#forChild

创建一个包含所有路由指令和提供者的模块注册路由.

Creates a module with all the router directives and a provider registering routes.

第一个通常用于为 Angular 应用创建初始配置并注册基本"路由,而第二个通常用于配置相对"路由.

The first is usually used to create the initial configuration for the Angular app and register the "base" routes while the second is usually used to configure "relative" routes.

假设我们有一个包含以下路线的应用:

Let's say we have an app with routes for:

  1. 用户
    • 注册
    • 列表
    • 删除
  • 注册
  • 列表
  • 删除

你可以像这样使用提到的方法:

You could use the mentioned methods like this:

app-routing.module.ts (这是一个真实"的应用程序,路由不同)

使用 RouterModule#forRoot

//...
const  routes: Routes = [
  {
    path: 'user', loadChildren: './user/user.module#userModule'
    // this lazy loading is deprecated in favor of
    // loadChildren: () => import('./user/user.module').then(m => m.UserModule) }
  },
  // same deprecation applies here
  { path: 'company', loadChildren: './company/company.module#CompanyModule'},
  // same deprecation applies here
  { path: '**', loadChildren: './page-not-found/page-not-found.module#PageNotFoundModule'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
//...

用户-routing.module.ts (这是一个真实"的应用程序,路由不同)

并且使用 RouterModule#forChild

//...
const routes: Routes = [
  { path: 'list', component: UserComponent},
  { path: 'delete/:id', component: UserDeleteComponent},
  { path: 'register/:id', component: UserRegisterComponent},
];

@NgModule({
  imports: [ RouterModule.forChild(routes) ],
  exports: [ RouterModule ]
})

//...

公司儿童路线也是如此.

And the same would go on for the Company children routes.

这篇关于Angular:forRoot/forChild 方法的用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆