resolver on lazy loading angular

喜夏-厌秋 提交于 2021-02-18 22:49:17

问题


is there a way to add a resolver before loading a lazy load module? i tried to add resolve to the routs configuration but it is not triggered, also didn't find any thing useful about it on the web. any help would be appreciated

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 { }

回答1:


Angular docs on lazy loading

This config always works for me. If this doesnt work there may be something wrong with your resolver.

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



回答2:


I have encountered the same issue. Here is an example of this issue in Stackblitz.com in Angular 9

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

The ChildResolver is set on the lazy-loaded route, but never gets called.


My workaround was to make a "lazyResolver" inside my guard.

So something like this in 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),
  );

}



来源:https://stackoverflow.com/questions/53346976/resolver-on-lazy-loading-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!