Jscti
Jscti

Reputation: 14440

Angular custom/delayed Lazy PreloadingStrategy bug

I can't understand why my preloading strategy is registered and loaded multiple times even after modules are already loaded ...

Standard PreloadAllModules from Angular source is :

export class PreloadAllModules implements PreloadingStrategy {
    preload(route: Route, fn: () => Observable<any>): Observable<any> {
        console.log('registering preload', route.path);
        function test() {
            console.log('preloading', route.path);
            return fn();
        }
        return _catch.call(test(), () => of(null));
    }
}

Here, both console.log will trigger only once for each of my lazy-routes, enfin if I navigate around my lazy-routes, it won't never re-run (normal).

My custom strategy, where I try to add a minimim delay to it :

export class PreloadAllModulesWithDelay implements PreloadingStrategy {
    preload(route: Route, fn: () => Observable<any>): Observable<any> {
        console.log('registering preload', route.path);
        return timer(5000).pipe(
            first(),
            map(() => {
                console.log('preloading', route.path);
                return _catch.call(fn(), () => of(null));
            })
        );
    }
}

Here, at first, the registering logs will be called, then 5s after the loading will be called, as intended. But after several routes change, the registering/loading will re-run, as if angular didn't save the modules conf.

Tried to debug angular core source without success.

Note: for those wondering, I'm creating this delayed strategy because angular lazy loads modules too quickly... it load them while my router animation is still performing and this results in a UI freeze for a few milliseconds (that breaks the fluidity of my animation).. That may be an angular bug.

Upvotes: 0

Views: 657

Answers (1)

Miller
Miller

Reputation: 2822

The problem is that map is returning a new inner Observable that angular doesn't know what to do with.

You should instead use switchMap or flatMap to flatten this out.

Upvotes: 3

Related Questions