将Angular 2路由转换为Angular 5

时间:2018-04-18 21:53:22

标签: angular angular-routing

我有一个网站,我正处于从Angular 2转换为Angular 5的过程中。我现在有一个问题是如何处理Angular 5中的预加载比较。例如,旧的角度2代码上的代码是:

       .state('data', {
        url: "/data",
        templateUrl: "data/data.tpl.html",*emphasized text*
        resolve: {
            preLoad:['dataService', function(service) {
                return service.primeData();
            }]
        },
        caption: "Search",
        navOrder: 1

我的问题是如何在Angular 5上处理preload:上面的内容。感谢您对此有任何意见或帮助。

2 个答案:

答案 0 :(得分:1)

要在 Angular 5 中预加载模块/服务,您可以通过路由配置来完成:

应用-routing.module.ts

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

import { DataComponent } from './data.component';
import { PageNotFoundComponent }   from './not-found.component';


const appRoutes: Routes = [
  {
    path: 'data',
    loadChildren: 'app/data/data.module#DataModule'
  },
  { path: '',   redirectTo: '/heroes', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

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

您可以启用预加载所有模块(或添加自己的自定义预加载):

RouterModule.forRoot(
  appRoutes,
  {
    enableTracing: true, // <-- debugging purposes only
    preloadingStrategy: PreloadAllModules
  }
)

答案 1 :(得分:0)

app.router.ts

import { NgModule ,ModuleWithProviders } from '@angular/core';

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

import { dataService } from './service/dataService';


const router: Routes = [
   { path: 'DataService, redirectTo: '/dashboard', pathMatch: 'full' },

   { 
      path: 'detail/:id', 
      component: HeroDetailComponent,
      resolve: {
        data: dataService 
      },
  }

];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule , APP_INITIALIZER    } from '@angular/core';

import {routes} from './app.router';

import { dataService } from './service/dataService';

@NgModule({

   declarations: [

      your component here 
   ],

   imports: [

      routes,

   ],

   providers: [

      dataService 

   ]

})
export class AppModule { }

dataService.ts

import { Injectable } from '@angular/core';

import { Router, Resolve, ActivatedRouteSnapshot} from '@angular/router';

@Injectable()

export class dataService implements Resolve {

   constructor(private heroService: HeroService, private router: Router) { }

   resolve(route: ActivatedRouteSnapshot): Promise | boolean {

      let id = route.params['id'];

      let result = this.check_id(id);

      if ( result ) {

          return result ;

      } else { // id not found

          this.router.navigate(['/dashboard']);

          return false;
      }

   }

 check_id(id){

     // check somthing return somthing or false

    return true;
 }
}