Angular 2 Routing - ModuleWithProviders v NgModule

aus*_*ive 9 angular2-routing angular

我正在通过Angular 2开发一个MEAN项目,我正在设置各种页面的路由.我已经看到很多使用ModuleWithProviders进行路由的示例,而不是使用NgModule的angular.io示例(https://angular.io/guide/router)

这是标准的做事方式?如果其中任何一个是可以接受的,两者之间是否存在性能差异?

ModuleWithProviders示例:

import { ModuleWithProviders } from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';

export const router: Routes = [
    { path: '', redirectTo: 'about', pathMatch: 'full'},
    { path: 'about', component: AboutComponent },
    { path: 'services', component: ServicesComponent }
];

export const routes: ModuleWithProviders = RouterModule.forRoot(router);
Run Code Online (Sandbox Code Playgroud)

NgModule示例:

import { NgModule } from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';

export const router: Routes = [
    { path: '', redirectTo: 'about', pathMatch: 'full'},
    { path: 'about', component: AboutComponent },
    { path: 'services', component: ServicesComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot( router )
  ],
  exports: [
    RouterModule
  ]
})

export class AppRoutingModule {}
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 10

NgModule和ModuleWithProviders是不同的东西.

NgModule 是模块类的装饰器.

ModuleWithProviders应该由forRoot方法返回的接口.ModuleWithProvidersobject是普通对象,其ngModule属性包含在providers属性中使用其他提供程序扩充的实际模块类.

由于ModuleWithProviders是一个接口,它的用法是可选的.


Bab*_*bak 10

estus对于两者之间的区别是完全正确的(@NgModule装饰者虽然ModuleWithProvider是界面)但实际上,你的问题的答案是哪种方法更好是:

第二种方法更清晰,更常见,也是最佳实践,因为它在单独的模块中定义了路径,稍后将其导入AppModule:

export const routes: Routes = [
    { path: '', redirectTo: 'about', pathMatch: 'full'},
    { path: 'about', component: AboutComponent },
    { path: 'services', component: ServicesComponent }
];

const config: ExtraOptions = {
  useHash: true
};

@NgModule({
  imports: [RouterModule.forRoot(routes, config)],
  exports: [RouterModule]
})    
export class AppRoutingModule {}
Run Code Online (Sandbox Code Playgroud)

导入到 AppModule

@NgModule({
  declarations: [AppComponent],
  imports: [AppRoutingModule],
  bootstrap: [AppComponent],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

虽然,上述提到的什么希望回答了你的问题,我想也指出,进口之间的差额RouterModuleAppModule和子模块:

对于AppModule:

RouterModule.forRoot(routes)
Run Code Online (Sandbox Code Playgroud)

对于子模块:

RouterModule.forChild(routes)
Run Code Online (Sandbox Code Playgroud)

为什么?RouterModule给你

  • 一个组件(路由器插座)
  • 一个指令(routerLink)
  • 还有服务(ActivatedRoute获取URL参数,路由器导航...)

第一次在app模块中,forRoot会给路由器组件并提供路由器服务.但是下一次子模块中,forChild只会给路由器组件(而不再提供已通过app模块导入提供的服务).

想要阅读更多?我发现这篇文章很神奇.