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

  • Providers tells Angular’s DI that we’d like to obtain an instance of the TicketService .
  • The method bootstrapModule is used to kickstart the app.
  • Finally we create the app by using a custom tag named my-app .
  • As time passes, just update your interface with the new routes needed.
  • /ticket.entity’; import {Injectable} from ‘@angular/core’; import {Http, Headers} from ‘@angular/http’; import ‘rxjs/add/operator/map’; @Injectable() 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 ‘, 0); this.http .post(‘http://localhost:8080/api/ticket’, JSON.stringify(newTicket), headers) .map(res => res.json()) .subscribe( data => this.tickets.push(data), err => this.logError(err), () => console.log(‘Updated Ticket’) ); } saveTicket(ticket: Ticket) { …

Look ma, no server! Don’t be held up waiting for the API to be built; Vildan Softic shows how to develop apps with the Angular 2 MockBackend class.

@JavaScriptKicks: Look Ma, No Server: Developing Apps with Angular 2 MockBackend by @sitepointdotcom #javascript #angularjs

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!

This article has been updated in line with the recent release of version 2.1.2 of Angular. The linked Plunkr example app has also been updated.

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.

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.

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.

Table 1: Consumed endpoints of the ticketing system

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

describing the ticket entity

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

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.

which, amongst other things, configures 3rd party dependencies and Angular’s application files. The Reactive Extensions (Rx) aren’t actually a true dependency but 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 this topic.

. Those are called Components and are somewhat comparable to Angular.JS 1.x directives.

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.

is used to state which component should be the entry point.

Finally, the method bootstrapModule is used to kickstart the app.

being used repeatedly to display multiple ticket entities.

class property, which will hold a set of fake Tickets.

. After that, we search for the given ID and reply with the corresponding ticket entity.

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.

will trigger the loading of all tickets when the component is fully rendered.

as well and getting the to be rendered entity.

, used to abstract the Ajax calls away from the components.

, mapping the result – which in this case will be the fake reply – and proceeding with the custom application logic.

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.

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.

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.

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

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.