Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions packages/core/src/di/inject_async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ export function injectAsync<T>(
};

if (options?.prefetch) {
options.prefetch().then(() => load());
options
.prefetch()
.then(() => load())
.catch(() => {});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should errors go to the error handler?

}

// We can't use `inject` later on because of the async nature of the loader
Expand Down Expand Up @@ -131,7 +134,7 @@ export type PrefetchTrigger = () => Promise<void>;
*/
export function onIdle(options?: {timeout?: number}): Promise<void> {
if (ngDevMode) {
assertInInjectionContext(injectAsync);
assertInInjectionContext(onIdle);
}

const idleService = inject(IDLE_SERVICE);
Expand Down
35 changes: 35 additions & 0 deletions packages/core/test/di/inject_async/inject_async_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,4 +301,39 @@ describe('injectAsync', () => {

jasmine.clock().uninstall();
});

it('should not cause an unhandled promise rejection if prefetch trigger rejects', async () => {
await TestBed.runInInjectionContext(async () => {
const fooPromise = injectAsync(() => Promise.resolve(FooService), {
prefetch: () => Promise.reject(new Error('prefetch error')),
});

await Promise.resolve();

const foo = await fooPromise();
expect(foo).toBeInstanceOf(FooService);
});
});

it('should not cause an unhandled promise rejection if loader rejects during prefetch', async () => {
await TestBed.runInInjectionContext(async () => {
const fooPromise = injectAsync(() => Promise.reject(new Error('loader error')), {
prefetch: () => Promise.resolve(),
});

await Promise.resolve();
await Promise.resolve();
await Promise.resolve();

let error!: Error;
try {
await fooPromise();
} catch (e: any) {
error = e;
}

expect(error).toBeDefined();
expect(error.message).toBe('loader error');
});
});
});
Loading