How to Build Server-Specific Services in Angular Universal
Once your MongoService is in place, you need to prepare a server-equivalent of ProductsService. This service will query MongoService for products list and descriptions and embed those in the HTML rendered by Angular Universal.
It's time to consume MongoService
. You could do this using the isPlatformServer()
and isPlatformBrowowser()
methods that you already know. The problem with this solution is that server-specific code is included in the main bundle that is shipped to the browser. In other words, this solution increases the size of the application delivered to the end user.
Fortunately, another technique is available. You are going to make use of AppServerModule
and provide the implementation of the ProductsService
interface that is specific to the server runtime.
Implementing the server-specific service#
Generate a new service using the following command:
ng g s products-server --skipTests
Copy the following service logic to src/app/products-server.service.ts:
this.ms.retrieveFromDb<Product>('products', {
This lesson preview is part of the The newline Guide to Angular Universal course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to The newline Guide to Angular Universal, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
