8

有没有办法在加载延迟加载模块之前添加解析器?我试图添加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 { }
4

2 回答 2

4

关于延迟加载的 Angular 文档

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

const routes: Routes = [
  {
    path: 'second',
    loadChildren: () => import('/second/second.module')
      .then(m => m.SecondModule),
    resolve: {
      data: SecondResolverService
    }
  },
于 2019-11-22T13:46:41.177 回答
1

我遇到了同样的问题。这是 Angular 9 中 Stackblitz.com 中的这个问题的示例

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

ChildResolver 设置在延迟加载的路由上,但永远不会被调用。


我的解决方法是在我的警卫内部制作一个“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),
  );

}

于 2020-06-15T23:22:03.983 回答