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

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

问题描述

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

forRoot / forChild 的方法是什么?

例如在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. 用户
    • 注册
    • 列表
    • 删除
  1. User
    • Register
    • List
    • Delete
  • 注册
  • 列表
  • 删除

您可以使用上述提到的方法:

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天全站免登陆