angular/packages/platform-server/src/http.ts
Andrew Kushnir 59837f4749 refactor(platform-server): import xhr2 dynamically in the ServerXhr class (#50095)
This commit updates the `@angular/common/http` and `@angular/platform-server` packages to allow dynamic import of the `xhr2` dependency. The `xhr2` dependency has side-effects that rely on a global scope and as a result in some environments those side-effectful calls fail. With the changes from this PR, the import is delayed until it's actually needed, which gives a chance for the underlying platform to setup global scope (via shims) as needed.

Co-authored-by: alan-agius4 <17563226+alan-agius4@users.noreply.github.com>

PR Close #50095
2023-05-08 14:32:43 -07:00

40 lines
1.1 KiB
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {XhrFactory} from '@angular/common';
import {Injectable, Provider} from '@angular/core';
@Injectable()
export class ServerXhr implements XhrFactory {
private xhrImpl: typeof import('xhr2')|undefined;
// The `xhr2` dependency has a side-effect of accessing and modifying a
// global scope. Loading `xhr2` dynamically allows us to delay the loading
// and start the process once the global scope is established by the underlying
// server platform (via shims, etc).
private async ɵloadImpl(): Promise<void> {
if (!this.xhrImpl) {
const {default: xhr} = await import('xhr2');
this.xhrImpl = xhr;
}
}
build(): XMLHttpRequest {
const impl = this.xhrImpl;
if (!impl) {
throw new Error('Unexpected state in ServerXhr: XHR implementation is not loaded.');
}
return new impl.XMLHttpRequest();
}
}
export const SERVER_HTTP_PROVIDERS: Provider[] = [
{provide: XhrFactory, useClass: ServerXhr},
];