Look Ma, No Server: Developing Apps with Angular 2 MockBackend

By Vildan Softic

This article was peer reviewed by Dan Prince and Rabi Kiran. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

Getting your front-end and back-end teams up to full speed is certainly something each company is looking for. Often though, what happens is that the teams fall into the pit of blocking dependencies. Those are situations where the upcoming work of one team is blocked by a user story owned by the other team.

One of those examples is the communication process between the front- and back-end. These days REST APIs have ascended the throne of so-called communication standards. The benefit of using JSON, a simple yet effective data transfer format, is that front-end workers do not need to care about the actual back-end anymore. Whatever crosses the wire is directly consumable and may be leveraged to bring data into your application. So it’s not surprising that those elementary entities often do not get modeled at all on the front-end and are consumed as they arrive. This brings us to the fundamental problem of having to wait for the back-end team to provide something useful. As depicted in the following figure, we see that both teams start in parallel, but at a certain time one team is kept waiting for the other to catch up.

Diagram showing how front-end tasks depend on the back-end team finishing the API

Besides this, having no kind of fixed structure makes each change a potentially dangerous one. So the focus of this article is to present a way that front-end teams can become independent of the back-end and at the same time provide a useful interface which reduces the risk of structural changes.

A Ticketing System without a Real Back-End

In order to achieve that independence it’s imperative to start thinking upfront about your project. What entities are you going to use? What communication endpoints result therefore?

This can be done by creating a small table highlighting the necessary REST endpoints and describing their purpose. Remember the reason we are doing that upfront is for both parties to agree upon a common structure for communication. That does not mean it has to be perfectly done but it should help you get started with the most important steps. As time passes, just update your interface accordingly with the new routes needed.

The actual process of creating a back-endless environment is to capture all HTTP requests and instead of letting them go out into the wild, reply with a fake response containing the information we’d like to have. This article will demonstrate the approach by describing a simple ticketing system. It uses the endpoints shown in the following table.

Please note that the example utilizes the POST verb for both the update and create route. Another option would be to leverage PUT for the update process. Keep in mind though that PUT should be idempotent, meaning every consecutive call has to produce the same result. Feel free to choose whatever suites your needs.

Method Route Request body Description
GET /ticket None Request all tickets
GET /ticket/:id None Request a single ticket via the provided :id parameter
POST /ticket Ticket entity Create a new or update an existing ticket
DELETE /ticket/:id None Delete a ticket, identified by the :id parameter

Table 1: Consumed endpoints of the ticketing system

The Ticket entity is a simple TypeScript class containing some basic ticket information:

export class Ticket {
  public _id: string;
  public title: string;
  public assignedTo: string;
  public description: string;
  public percentageComplete: number;

  constructor(id: string, title: string, assignedTo: string,
        description: string, percentageComplete: number) {
    this._id = id;
    this.title = title;
    this.assignedTo = assignedTo;
    this.description = description;
    this.percentageComplete = percentageComplete;

ticket.entity.ts describing the ticket entity

You may find the complete code as well as a preview for this example on Plunker:

The Angular 2 Project Setup

Enough theory, lets get our hands dirty with some coding. The project structure shown here is built upon the proposed Angular 2 Getting Started guide. As such, we won’t waste too much time explaining every part of it. If you’re searching for a introductory article, take a look at Getting Started with Angular 2 using TypeScript. For this article, you can just open up the above mentioned Plunker to follow the code parts explained below.

As most single page applications start with an index.html file, lets take a look at it first. The first section imports the necessary 3rd party dependencies and Angular’s application files located in the vendor sub-folder. The Reactive Extensions (Rx) aren’t actually a true dependency but will simplify the work with Angular’s observables, which are the replacement for the previously used Promises. I highly recommend this article by Cory Rylan to learn more about the topic.

Note that manual script referencing is not the recommended way to create production-ready apps, nor is the framework itself either, being in beta state. You should use a package manager like npm or jspm. The later one works hand in hand with SystemJS, described in section two. SystemJS is a module loader previously based on the ECMAScript 2015 draft and now part of WHATWG’s Loader specification. As such, it enables the use of the import x from 'module' syntax. In order to use it properly we need to configure it and then import the application’s main entry point, the file app/boot.ts.

Note that we configured the defaultExtension so that we can omit the file extension in our import statements.

Finally we create the app by using a custom tag named my-app. Those are called Components and are somewhat comparable to Angular.JS 1.x directives.

<!DOCTYPE html>

    <title>ng2 Ticketing System</title>

    <!-- 1. Load libraries -->
    <script src="vendor/angular2-polyfills.js"></script>
    <script src="vendor/system.js"></script>
    <script src="vendor/typescript.js"></script>
    <script src="vendor/Rx.js"></script>
    <script src="vendor/"></script>
    <script src="vendor/"></script>
    <script src="vendor/"></script>
    <script src="vendor/lodash.min.js"></script>

    <!-- 2. Configure SystemJS -->
        transpiler: 'typescript', 
        typescriptOptions: { emitDecoratorMetadata: true }, 
        packages: {'app': {defaultExtension: 'ts'}} 
            .then(null, console.error.bind(console));

    <meta charset="utf-8">
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">


  <!-- 3. Display the application -->
    <my-app>Loading ...</my-app>

The file boot.ts is used to bootstrap Angular into the my-app component. Together with all application specific code it is located inside the folder app. Inside boot.ts we’re going to perform the first steps necessary in order to leverage a mocked back-end, which will act as a substitute for the real back-end.

The provide function is used to tell Angular’s DI (dependency injection) system which actual instance of a class we’d like to use and what dependencies it requires. If we look at the line where provide() creates a custom instance of the Http service, we can see that the requested dependencies (deps), which are injected right before the call to provide(), are passed on to the useFactory method. Those are then used to create a new instance of Http.

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {MockBackend} from 'angular2/http/testing';
import {HTTP_PROVIDERS, Http, BaseRequestOptions} from 'angular2/http';
import {AppComponent} from './app.component'

bootstrap(AppComponent, [
  provide(Http, {
    deps: [MockBackend, BaseRequestOptions]
    useFactory: (backend, options) => {
      return new Http(backend, options);

The class MockBackend is originally meant to be used in unit testing scenarios, in order to mock real server calls and therefore keep unit test runs quick and isolated. You can read more about this in the official Http Documentation

Working with Components

It’s now time to take a look at the finished application to identify the components we’re going to work with. As with every Angular 2 application, there is a so-called AppComponent, which acts as the main entry point into one’s application. It also can be used as a container, showing the general navigation and hosting sub-components. Speaking of those, we can see the TicketComponent being used repeatedly to display multiple ticket entities.

Screenshot of the ticket system, highlighting the separate components

The app component used with the selector my-app and pointing to a template index.html, located in the templates sub-folder. The directives property indicates the dependency on the sub-component TicketComponent. Finally providers tells Angular’s DI that we’d like to obtain an instance of the TicketService.


  selector: 'my-app',
  templateUrl: 'app/templates/index.html',
  directives: [TicketComponent],
  providers: [TicketService]
export class AppComponent {

Next we define a db class property, which will hold a set of fake Tickets.

// Fake Tickets DB
private db: Ticket[] = [
  new Ticket(
    '1', 'Missing Exception', 'John Smith',
    'Method XYZ should throw exception in case ABC', 0),
  new Ticket(
    '2', 'Log errors', 'John Smith',
    'Logs need to be persisted to a local file', 24),
  new Ticket(
    '3', 'Update AngularJS', 'John Smith',
    'Need to update the App to AngularJS version 1.5', 0),
  new Ticket(
    '4', 'Border is missing', 'Jane Doe',
    'The element div.demo has no border defined', 100),
  new Ticket(
    '5', 'Introduce responsive grid', 'Jane Doe',
    'Implement reponsive grid for better displays on mobile devices', 17)

The constructor now receives the injected TicketService as well as the fake backend. In here we now subscribe to the connections stream. For each outgoing request we’re now going to check it’s request.method and request.url in order to find out what type of endpoint is requested. If the proper route is matched, we reply using the mockRespond method with a new Response containing the expected result as body.

constructor(private service: TicketService, private backend: MockBackend) {   
  this.backend.connections.subscribe( c => {

    let singleTicketMatcher = /\/api\/ticket\/([0-9]+)/i;        

    // return all tickets
    // GET: /ticket
    if (c.request.url === "http://localhost:8080/api/ticket" && c.request.method === 0) {
      let res = new Response({
        body: JSON.stringify(this.db)


When requesting a single ticket, we use the singleTicketMatcher defined above in order to perform a regex search on the request.url. After that, we search for the given ID and reply with the corresponding ticket entity.

// return ticket matching the given id
// GET: /ticket/:id
else if (c.request.url.match(singleTicketMatcher) && c.request.method === 0) {
  let matches = this.db.filter( (t) => {
    return t._id == c.request.url.match(singleTicketMatcher)[1]

  c.mockRespond(new Response({
    body: JSON.stringify(matches[0])

In case of updates and the creation of new tickets, we get the ticket entity delivered via the request body instead of a query parameter or URL pattern. Besides that, the work is pretty simple. We first check whether the ticket already exists and update it, otherwise we create a new one and send it back with the response. We do this in order to inform the requester about the new Ticket ID.

    // Add or update a ticket
    // POST: /ticket
    else if (c.request.url === 'http://localhost:8080/api/ticket' 
         && c.request.method === 1) {
      let newTicket: Ticket = JSON.parse(c.request._body);

      let existingTicket = this.db.filter( 
        (ticket: Ticket) => { return ticket._id == newTicket._id}
      if (existingTicket && existingTicket.length === 1) {
        Object.assign(existingTicket[0], newTicket);

        c.mockRespond(new Response({
          body: JSON.stringify(existingTicket[0])
      } else {
        newTicket._id = parseInt(_.max(this.db, function(t) {
          return t._id;
        })._id || 0, 10) + 1 + '';


        c.mockRespond(new Response({
          body: JSON.stringify(newTicket)
    // Delete a ticket
    // DELETE: /ticket/:id
    else if (c.request.url.match(singleTicketMatcher) && c.request.method === 3) {
      let ticketId = c.request.url.match(singleTicketMatcher)[1];
      let pos = _.indexOf(_.pluck(this.db, '_id'), ticketId);

      this.db.splice(pos, 1);

      c.mockRespond(new Response({
        body: JSON.stringify({})


Last but not least the page life cycle hook ngOnInit will trigger the loading of all tickets when the component is fully rendered.

public ngOnInit() {

In a real production app you would separate the mock setup into a separate service and inject it as a dependency into the AppComponent. This was omitted in order to keep the demo simpler.

Looking at the TicketComponent we can see that nothing too interesting happens, besides the Component decorator. We define ticket as the selector and again point to a separate template file. Now, in contrast to the AppComponent, we expect a ticket tag to be created with an attribute named title as well and getting the to be rendered entity.

The constructor then finally gets the TicketService injected and assigns it to a class property service.

import {Component} from 'angular2/core';
import {Ticket} from './ticket.entity';
import {TicketService} from './ticket.service';

  selector: 'ticket',
  templateUrl: 'app/templates/ticket.html',
  inputs: ['ticket'],
  //providers: [TicketService] <-- this would override the parent DI instance
export class TicketComponent {
  public ticket: Ticket;

  constructor(private service: TicketService) { }

The Ticket Service

The last thing missing is the TicketService, used to abstract the Ajax calls away from the components.
As we can see it expects the http service to be injected. Now, remembering the initial boot.ts file we know that the instance provided will be the one with the mocked back-end. The actual request stays the same by leveraging the HTTP services request methods like post or get, mapping the result – which in this case will be the fake reply – and proceeding with the custom application logic.

import {Ticket} from './ticket.entity';
import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import 'rxjs/add/operator/map';

export class TicketService {
  tickets: Ticket[] = [];

  constructor(private http: Http) {


  addNewTicket() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    var newTicket = new Ticket("0", 'New Ticket', 'Nobody', 
      'Enter ticket description here', 0);
      .post('http://localhost:8080/api/ticket', JSON.stringify(newTicket), headers)
      .map(res => res.json())
        data =>,
        err => this.logError(err),
        () => console.log('Updated Ticket')

  saveTicket(ticket: Ticket) {

  deleteTicket(ticket: Ticket) {

  loadAllTickets() {

  loadTicketById(id) {

  logError(err) {
    console.error('There was an error: ' + err);


Summing up, we saw how Angular’s dependency injection can help us to replace the default XHRBackend of the HTTP service with a mocked back-end. Inside the AppComponent we then created our fake database, intercepted every outgoing request, and replied with a custom fake response. The benefits we’ve gained are now complete independence from the back-end team and, at the same time, a defined interface. Now, once the production back-end is in place, all we need to do is to remove the dependency injection override and faked back-end, and we’re good to go.

  • Gerard Sans

    Awesome! Url interception looking raw at the moment though.

  • Vildan Softic

    Yep, I’m sure there’s a nice NPM package out there to handle this more nicely. But I felt like it’s important to show the barebone approach. Thanks for the comment though +1

  • Vildan Softic

    the idea actually is somewhat different. When you create your own custom backend e.g. with one of the million different NPM rest api modules you actually create a hard dependency. When it’s time to switch to the real backend you’d have to go all-in and change the service base-url. Alternatively you can maintain a second version of the BackendService and switch it.
    Nevertheless the issue pertains that you’d go all-in when switching.

    The demonstrated approach in this article allows you not only to omit having an additional server (what if you’re not working with Node and prefer a backends with Go?), maintain and include it in your dev-setup but also allows you to switch from mocked to real implementations on a per endpoint basis.

    So it’s definitely up to ones own preference and circumstances but having a full frontend solution vs a Frontend [Real || Fake] might be easier to handle in the long run.

    • markbrown4

      No hard dependencies, json-server is only for prototyping and is meant to be thrown away. This approach requires a lot of custom code to mock the backend, something like json-server requires zero.

      • Vildan Softic

        I think you’ve not read my reply to the end but stopped right after the words “hard dependency” :) It’s not about faking a backend by implementing another one, but about removing it at all until the final one is done partially or in full. Just another way to solve the problem, never said it’s the best :)

  • Sky

    Vildan, thanks for the awesome walkthrough. I was looking for an Angular 2 equivalent to Ember Mirage, and I was successful in implementing very similar syntax and functionality thanks to this post. I set up mocking to be provided based on environment flag, as we maintain our mock code to facilitate ongoing UI development, not “cut over” at some point.

    I encountered 2 discrepancies I thought I would share:

    1) Your provide syntax has been deprecated,

    provide(Http, {
    deps: [MockBackend, BaseRequestOptions]
    useFactory: (backend, options) => {
    return new Http(backend, options);

    should become:

    provide: Http,
    deps: [MockBackend, BaseRequestOptions],
    useFactory: (backend, options) => {
    return new Http(backend, options);

    2) Response takes a ResponseOptions parameter,

    c.mockRespond(new Response({
    body: JSON.stringify(matches[0])

    should become:

    c.mockRespond(new ResponseOptions({
    body: JSON.stringify(matches[0])

    Other than that, everything went smoothly. Thanks!

    • Anjum Naseer

      I am using Angular 2.0.1 and had to change this:
      > import {bootstrap} from ‘angular2/platform/browser’;
      > import {provide} from ‘angular2/core’;
      > import {MockBackend} from ‘angular2/http/testing’;
      > import {HTTP_PROVIDERS, Http, BaseRequestOptions} from ‘angular2/http’;
      > import {AppComponent} from ‘./app.component’
      > bootstrap(AppComponent, [
      > BaseRequestOptions,
      > MockBackend,
      > provide(Http, {
      > deps: [MockBackend, BaseRequestOptions]
      > useFactory: (backend, options) => {
      > return new Http(backend, options);
      > },
      > })
      > ]);

      > import { MockBackend } from ‘@angular/http/testing’;
      > import { Http, BaseRequestOptions } from ‘@angular/http’;
      > …
      > @NgModule({
      > …,
      > providers: [
      > BaseRequestOptions,
      > MockBackend,
      > {
      > provide: Http,
      > deps: [MockBackend, BaseRequestOptions],
      > useFactory: (backend, options) => { return new Http(backend, options); }
      > }
      > ],
      > bootstrap: [AppComponent]
      > })

      • Vildan Softic

        Thanks for the update instruction

  • Victor

    Thanks Vildan, for the nice write up. But I have a doubt. When we use MockBackend, none of the HTTP requests are going out of browser right? How can we allow all other URLs to pass through, if we are not catching them explicitly using url matching? Example use case is to load configurations or translations from a local JSON file.

    • Jonathan Fishbein

      Victor, maybe this may help, both systemjs and webpack support loading json files as dependencies

  • Jonathan Fishbein

    Thanks Vildan for the post. I am attempting to follow your example. I was looking for a solution like this. I watch Pluralsight videos and in the videos they are creating a mock api but it’s just a class that has methods that return data often wrapped in a Promise. Although useful, as you said if creates hard dependency. Currently I’m trying your method on my own project but I’m running into some difficulties and getting a 404 when attempting to _http.get(url) so something’s wrong where it’s not being intercepted. Any ideas? Thanks!

  • Eapen john

    Hi Vildan,

    thanks for the blog it works very well. I am trying to setup a mock backend for my e2e, so ultimately the mockbackend will serve all requests during the tests. So is it possible separate the all mockups in a module and load during the init of the app?

    Eapen John

    • Vildan Softic

      Havent tried but I’m pretty sure you can. If you follow the update notes posted by Anjum Naseer you see how to conform to the new NgModule style, introduced with RC5. So ultimately this should be the way to wrap your mockbackend registration. Now the example depicted in this article was just meant to give the reader a quick intro in how this works. Of course you can refactor all the parts from the app component, to be inside another “FakeService” which then would do all the setting up and maintaining of the fakeDB. You’d then simply wire that new service into your NgModule.



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.