Angular Universal fallbacks
Part of
Web APIs for Angular
A set of fallbacks to seamlessly use @ng-web-apis/common in Angular Universal apps. These packages have synced versions down to minor.
How to use
Add constants imported from this package to providers of your ServerAppModule
.
Typically, you can also use these mocks for tests. Idea of this package is — you shouldn't
have to mock DOM on the server side or test isPLatformBrowser
all the time. Instead,
you leverage Angular DI system to abstract from implementation. When possible, this package
will provide the same functionality on the server side as you have in browser. In other cases
you will get type-safe mocks and you can at least be sure you will not have
cannot read propery of null
or undefined is not a function
errors in SSR.
Mocks
Add following line to your server.ts
to mock native classes used in other @ng-web-apis packages:
import '@ng-web-apis/universal/mocks';
Tokens
WINDOW
— no need to provide fallback, Angular Universal handles itNAVIGATOR
— addUNIVERSAL_NAVIGATOR
to provide type-safe mock object, effectively mocking allnavigator
related entitiesNETWORK_INFORMATION
— no need to do anythingUSER_AGENT
— see special cases belowPERFORMANCE
— addUNIVERSAL_PERFORMANCE
to use Node.jsPerformance
class on Server SideANIMATION_FRAME
— addUNIVERSAL_ANIMATION_FRAME
to fallback toNEVER
in SSR environmentCSS
— no need to do anything, mock object is already injected as if you were using Internet ExplorerLOCATION
— see special cases belowLOCAL_STORAGE
— addUNIVERSAL_LOCAL_STORAGE
for aMap
based mock forwindow.localStorage
SESSION_STORAGE
— addUNIVERSAL_SESSION_STORAGE
for aMap
based mock forwindow.sessionStorage
SPEECH_RECOGNITION
— no need to do anythingSPEECH_SYNTHESIS
— addUNIVERSAL_SPEECH_SYNTHESIS
for a type-safe mock forwindow.speechSynthesis
PAGE_VISIBILITY
— no need to do anything
You can also provide all the tokens at once with UNIVERSAL_PROVIDERS
constant
Special cases
When you use plain SSR without prerender you can retrieve some of the information
from requests. You can couple UNIVERSAL_NAVIGATOR
, UNIVERSAL_USER_AGENT
and
UNIVERSAL_LOCATION
providers with following helpers to harvest that info:
server.ts:
app.get('/**/*', (req: Request, res: Response) => {
res.render('../dist/index', {
req,
res,
providers: [provideLocation(req), provideUserAgent(req)],
});
});
app.server.module.ts
@NgModule({
imports: [AppModule, ServerModule],
bootstrap: [AppComponent],
providers: [UNIVERSAL_NAVIGATOR, UNIVERSAL_USER_AGENT, UNIVERSAL_LOCATION],
})
export class ServerAppModule {}