Since Angular 2.0 beta is out, let’s see how to write a simple CRUD application using Angular 2.0 beta.

Why Angular 2.0?

Angular 2.0 will be significantly faster and more memory efficient than Angular 1.x, as a result of removal of various modules from the core library. We should be able to pick and choose the modules we need as necessary. Angular 2.0 is written in Typescript which is a superset of ES6. Since the web is moving towards ES6, this is a great transition. Since Typescript is a statically typed language, we will get compile time errors and this feature is very useful when you have a big team writing thousands of lines of code. Similar to React, Angular 2.0 prefers component based UI. This makes it fitting to design our app into Presentational and Container components i.e., with Presentational components rarely having a state of their own and Container components acting as a data source to Presentational components.

For the purpose of this tutorial I will use Parse as the backend. Parse is

  • Incredibly cheap for low volumes.
  • Since it uses MongoDB NoSQL DB behind the scenes, it’s really easy to use.
  • Great documentation and excellent tutorials.
  • Parse push and analytics services are really good.

Parse Setup

First step is to create an app in Parse. Parse will ask you to create an account if you do not have one. Go ahead and create an app, I have named it angular-test. After creating your app, create an object called “Person” with FullName, Age, Email and Address as fields. Next, we will need the REST API Key and Application ID to make RESTful calls using angular’s HTTP service. Go to Settings page on Parse dashboard and note the keys.

Parse Settings

Demo

My demo is rather simple, we have a users list component that shows a list of all users in the system. Users list has an “Add” button that should navigate to an add screen. Users list also has a “delete” link to delete a specific user. Clicking on user full name should navigate to details screen where we can modify an existing user.

Angular 2.0 Setup

I am assuming you know you are familiar with setting up and bootstrapping an Angular 2.0 app. To set up an angular 2.0 beta development environment, please follow the official guide .

Firstly we should create a new directory called angular-test .Run npm init to initialize package.json file and copy the contents from repo. This is my package.json file.

package.json

Since we are using the Typescript compiler for this app, we need to copy the tsconfig.json file to our root folder as well.

Open command prompt from the newly created angular-test folder and run npm i to install the dependencies and we are good to go.

User Component

We need to start with showing a user list. So let’s start with creating a user component. We will be keeping our application code in a sub folder called app, so let’s create this folder. Create one more folder called components and add a file called user.ts. This will be the component responsible to show the list of users.

Remember, in the beginning of my blog I mentioned about component based UI ? Components replace controllers, scopes and directives from angular 1.x. We can identify a component as a class that represents a UI element, with annotations(meta-data) to describe it’s intend, it’s dependencies, it’s template etc. You can read more about components here.

User component

Side Notes:

  • I am using a remote html template named user.html for this component and you can view the full code in repo.
  • Components shouldn’t be making server calls that is the responsibility of services. I have a created a UserService for this purpose and i am injecting this service in constructor.
  • I am making a call to get all users in ngOnInit call, which is a method called by angular shortly after creating an instance of User component.
  • We need to store user data in a model, I created a model called UserItem in models folder, to store user data that is retrieved after a server call.

The basic structure of our app will look as follows.

User Service

UserService.ts

We will use the Angular Http client to communicate with the Parse server so we need to inject it into UserService constructor and initialize the http variable. You may notice the @Injectable decorator above UserService class. Since we are injecting Http client in service constructor, angular requires constructor parameter metadata to inject the Http client.

Other option is to Inject Http like this.

I find the first method more cleaner.

Side Notes:

  • Parse Restful service requires authentication to be enabled by HTTP headers.
  • You can see in code snippet above that i am passing X-Parse-Application-Id and X-Parse-REST-API-Key as headers, since authentication is done via HTTP headers in Parse.
You can see the complete Parse Rest documentation here https://parse.com/docs/rest/guide

If you recall, Angular 1 uses promises for async calls, but here in the above get call, you don’t see any promise .success or .error handlers ! Angular 2 team decided to use Reactive Programming by making use of RxJs library from Microsoft. Instead of async service calls returning a promise, http.get() in this scenario, returns an Observable ,which can be then manipulated by using method chaining like .map or .filter to form your desired data.

In our demo sample, since we have to populate the users list, we are mapping the Observable to a list of UserItem, which can be fed back to the User component in the subscribe method. Subscribe here is like the “listen” event in this scenario. So we can see an Observable is promise++ and are powerful as promises. Using a conventional debugger, it is arduous to debug RxJs. One technique we can use is to add a .do(x => console.log(x)) between operators. This technique is shown below.

Side Note:

We will have to import do from RxJs before we use this approach.

import ‘rxjs/add/operator/do’;

egghead.io has a good series on Reactive Programming by André Staltz

Routing

Our Home page template has a “Users” link. There should be a mechanism to navigate to User list screen when clicked on this link. We should also configure to navigate to Add User screen, when the user clicks the add button. Let us enable Route configuration.


app.ts

As you can see I am configuring the top level component app.ts, with 2 route definitions. The route definition defines the path to the route, name of the route and the component that is mapped to the route.

app.html

Our top level component app.html has a routerLink directive, which contains the name of the route definition. In our scenario, if we click the Users link, router will resolve this to a URL and a component view called “User”, and displays the user list inside router-outlet directive which is placed in our root view app.html. router-outer serves as placeholders for views to render our components.

Finally, before I conclude, I would like to show how to write unit test against User component along with the service call.

For setting up Unit Testing in angular 2.0 using Jasmine, please refer the official angular guide for testing.

In our code sample above, since our user component injects a UserService, we will have to provide a Mock user service which has a getUsers() function that return a dummy users list. Since our real user service getUsers() call returns an Observable, I am creating a dummy Observable from _users list using Obsersvable.from operator.

Then finally we need Jasmine to spy on getUsers() call which expects an Observable as return value.

Since the UserService injects Http in its constructor, we should provide a mock Http backend and inject it as shown in Unit Testing snippet above. You may notice I am overriding our User Html template with a fake Html template .Currently there is a bug in unit testing components with remote templates using templateUrl. Overriding the template with a fake template will get rid of this problem.

I hope this tutorial was useful for you.

You can view the complete working project including unit tests in https://github.com/rajvirtual/angular-test.

Thanks to Jeremy Likness