Set up a Http service for backendless development in Angular 2+

A backendless development with mocks is very handy for prototypes, demo applications, unit testing and more scenarios. I have already blogged about how to fake HTTP backend implementation in AngularJS 1. But how to achieve the same in Angular 2+? This story was inspired by the blog post Angular 2 — MockBackend Example for Backendless Development. I have adopted the proposed implementation for my book “Learning Angular UI Development with PrimeNG”. An example in the chapter 9 demonstrates a CRUD (create, read, update, delete) scenario with employees that are taken as domain model objects. Employees can be fetched, created, updated and deleted. All CRUD operations happens via Angular’s Http service which communicates with a mock backend.

The domain model object Employee is defined by the following interface.

The EmployeeService with CRUD operations exposes four methods with Observable as return value so that the component class can invoke subscribe() to receive delivered data.

Before implementing a fake or mock Http service, we need data. Let’s create a mock database as simple array of employees objects.

The mock Http service can be implemented with a factory method. We just need to use the following fakeBackendFactory method in place of standard Http service.

As you can see, there is a TODO in the code. Let’s implement the missing mapping from request URLs to mock data. This can be done with MockConnection from the package @angular/http/testing. We check requested URLs to the fake backend and return (modified) mock data. Requests, we are not interested in, can be passed through (real remote calls).

The last step — register the fake backend as provider:

The complete demo application with instructions is available on GitHub at: