延迟加载解析器 angular

resolver on lazy loading angular

有没有办法在加载延迟加载模块之前添加解析器?我试图将 resolve 添加到 routs 配置,但它没有被触发,也没有在网上找到任何有用的东西。任何帮助将不胜感激

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// services
import {SecondResolverService} from "./second.resolver.service";

const routes: Routes = [
  { path: 'first' , loadChildren: './first/first.module#FirstModule' },
  { path: 'second', loadChildren: './second/second.module#SecondModule' ,resolve : {data : SecondResolverService}}
];

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

Angular docs on lazy loading

这个配置对我一直有效。 如果这不起作用,则可能是您的解析器有问题。

const routes: Routes = [
  {
    path: 'second',
    loadChildren: () => import('/second/second.module')
      .then(m => m.SecondModule),
    resolve: {
      data: SecondResolverService
    }
  },

我遇到了同样的问题。这是 Stackblitz.com in Angular 9

中此问题的示例

https://stackblitz.com/edit/angular-ivy-ubes1q?file=src%2Fapp%2Fapp.module.ts

ChildResolver 设置在延迟加载的路由上,但从未被调用。


我的解决方法是在我的 guard 中创建一个“lazyResolver”。

所以在 data.guard.ts 中是这样的:

export class MyGuard implements CanActivate, CanActivateChild {

  constructor(
    private router: Router,
    private authService: AuthService,
    private myService: MyService,
  ) { }

  public canActivate(route, state): Observable<boolean | UrlTree> {
    return this.lazyResolver$().pipe(
      map(data => {
        // now we lazy resolved!
        return true;
      }),
      take(1),
      catchError(error => EMPTY),
    );
  }

  // safeguard when using resolvers and guards with lazy-loaded modules
  private lazyResolver$(): Observable<any> {
    return new MyResolver(this.myService).resolve(route, state),
  );

}