The Ultimate Guide For Native App Development

Previously on Angular 2: How Do Components Communicate I explained the different methods for Angular 2 Components to communicate between each other, either from parent to child, child to parent or by using injectable services and RxJS.

Now I want you to read this very carefullyWhat I’m going to show you today is something that no one has ever done or even tried before.

Today for the very first time I’m going to show you how to integrate MongoDB with the IBM StrongLoop’s LoopBack Framework, NativeScript 2 and Angular 2 to build truly Native Mobile Applications using the MEAN Stack in less than 50 lines of code!!!

[Public Applauses and Expectation in the Background]

Project Description

The objective of this tutorial is to show you a wonderful way to build truly native apps using the MEAN Stack, therefore I don’t want to create a really complex project, otherwise things can get a little bit overwhelming.

So.. I know everybody has ever built a Todo List App and that is why I want to use this as demo application, because in that way you don’t lose time and effort understanding a more complex application.

Instead we will focus on the technologies and the setup so you can build your own Native Mobile Applications using the MEAN Stack like a MEAN Expert.

Technology Stack

  • MongoDB.- Building on the Best of Relational with the Innovations of NoSQL.
  • LoopBack.- The Node.js API Framework.
  • Angular 2.- Development platform for building mobile and desktop applications.
  • NativeScript 2.- Truly native mobile apps with Angular.

Requirements

GitHub Example Code Repository

StrongLoop and NativeScript Integration

Setup Environment

Ok since you already have installed the environment stack, now we need to install the platforms needed for this project, for this we are going to use NPM.

1
$ npm install -g strongloop nativescript

Setup DataBase

Once you have installed and running MongoDB you need to setup an instance by using the following commands in a terminal.

1
2
3
4
5
6
$ mongo

> use todo-db
switched to db todo-db

> db.createUser({ user: 'todo-user', pwd: 'todo-pass', roles: ['readWrite'] });

Of course you can do this in your local machine or in a remote server, also use more secure credentials that are not for demo purposes.

Setup REST API Project

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
$ mkdir todo
$ mkdir todo/todo-api
$ cd todo/todo-api
$ slc loopback


_-----_
| | .--------------------------.
|--(o)--| | Let's create a LoopBack |
`---------´ | application! |
( _´U`_ ) '--------------------------'
/___A___\
| ~ |
__'.___.'__
´ ` |° ´ Y `

? What's the name of your application? todo-api

? What kind of application do you have in mind? api-server (A LoopBack API server with local User auth)
Generating .yo-rc.json


I'm all done. Running npm install for you to install the required dependencies. If this fails, try running the command yourself.


create .editorconfig
create .jshintignore
create .jshintrc
create server/boot/root.js
create server/middleware.json
create server/middleware.production.json
create server/server.js
create README.md
create server/boot/authentication.js
create .gitignore
create client/README.md
todo-api@1.0.0 /Volumes/backup/development/www/mean.expert/examples/todo/todo-api

Next steps:

Create a model in your app
$ slc loopback:model

Compose your API, run, deploy, profile, and monitor it with Arc
$ slc arc

Run the app
$ node .

We have just created a LoopBack Application, if you run the $ node . command, you will have a fully working RESTful API running in your machine/server that includes built in User Model, Authentication mechanism and API Explorer. But we still need to configure a datasource to connect with our MongoDB Instance.

For those who doesn’t know The StrongLoop‘s LoopBack Framework but you come from languages like PHP or Ruby Lang and you use Laravel, Ruby on Rails or from any language but you know the Active Record Pattern, well.. if you love these frameworks, or you love the Active Record Pattern, this is the framework in node that implements it the best, so you should be loving it by now.

Configure DataSource

In order to persist the information we create from the Client Application; we need to create a datasource that connects with MongoDB.

1
2
3
4
5
6
7
8
9
10
11
$ slc loopback:datasource
? Enter the data-source name: mongodb
? Select the connector for mongodb: MongoDB (supported by StrongLoop)
Connector-specific configuration:
? host: localhost
? port: 27017
? user: todo-user
? password: *********
? database: todo-db
? Install loopback-connector-mongodb@^1.4 Yes
└─ loopback-connector-mongodb@1.15.2

Create Todo Model

Remember we are creating a really simple app, since our goal is to get to know how to build truly native applications using the MEAN Stack, so for this project we are going to create just a model named Todo.

But if you like this post and you request me on Twitter I can build a much more complex application with relationships, acls and more.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ slc loopback:model Todo
? Enter the model name: Todo
? Select the data-source to attach Todo to: mongodb (mongodb)
? Select model's base class PersistedModel
? Expose Todo via the REST API? Yes
? Custom plural form (used to build REST URL): todos
? Common model or server only? common
Let's add some Todo properties now.


Enter an empty property name when done.
? Property name: text
invoke loopback:property
? Property type: string
? Required? Yes
? Default value[leave blank for none]:

Let's add another Todo property.
Enter an empty property name when done.
? Property name:

Configure The NativeScript 2 SDK Builder

A wonderful feature from the LoopBack Framework is the loopback-sdk-angular which automatically maps your RESTful API’s endpoints and provides you with a set of services compatible with AngularJS 1.

Hey wait, but aren’t we going to use NativeScript 2 with Angular 2? Well, thanks to community contributions in order to support Angular 2-Beta and that I forked the module and added support also for Angular 2-RC and for NativeScript 2, now everyone can automatically build an SDK for NativeScript with the minimum effort.

Install SDK Builder

1
$ npm install --save-dev @mean-expert/loopback-sdk-builder

Create NativeScript Application

Before we build the SDK lets first create our NativeScript 2 Application.

But what is so fantastic about NativeScript 2… Well these guys really did it. Finally we are able to build truly native mobile applications using JavaScript TypeScript.

If we compare with other technologies like Ionic that renders over a WebView; NativeScript renders using native components, giving you access to native API’s for the different mobile platforms like android and ios, what else can you ask for?

Lets create our NativeScript 2 Application:

1
2
$ cd ../
$ tns create todo-app --ng

That will create a new folder todo-app with our NativeScript 2 Scaffolded Application and the following folder structure:

1
2
3
4
5
$ ls -la
drwxr-xr-x 4 user staff 136 May 25 18:33 .
drwxr-xr-x 8 user staff 272 May 25 16:38 ..
drwxr-xr-x 13 user staff 442 May 25 18:35 todo-api
drwxr-xr-x 9 user staff 306 May 25 18:33 todo-app

Build SDK

It is time to do some magic and automatically create a SDK that will allow us to call every method within our backend from our mobile application, saving us hours of development in terms of client services.

1
2
$ cd todo-api
$ ./node_modules/.bin/lb-sdk server/server.js ../todo-app/app/sdk -d nativescript2

Wow!!! that’s it.. HABEMUS SDK… brilliant!! we just saved ourselves hours of bugs, pain and development in terms of building client services, by now you are a Super HERO and you built a set of fully working API services with full support for NativeScript 2 SDK in place.
[Applauses and Cheering sounds in the background]

Actually… Do you remember coding anything to have a fully working REST API or Client SDK? I know you won’t… But don’t worry if you feel your developer skills has not been challenged just yet, there are plenty of challenges to come.

Now if you are curious and open the sdk todo-app/app/sdk you will see it comes with a set of @Injectable services fully compatible with the Angular 2-RC Version and also with NativeScript 2 out of the box.

Important: If you want to build a web application that will render in a browser, then you should use -d ng4web when building the sdk.

Install @angular/http

If you are using Visual Studio Code or any IDE with plugings or support for TypeScript… You should be able to see the error mark referring to the missing HTTP Library from @angular, so lets install the dependency.

1
2
$ cd ../todo-app
$ npm install --save @angular/http

Develop Mobile Application

Finally we are set with everything we need to start building a native app, focusing ourselves in creating the views and adding some logic by using the NativeScript SDK we built just before.

Thanks to the fact that Angular 2 is not DOM dependent anymore, the guys from NativeScript did a wonderful job by integrating this super cool platform to allow us build truly native apps using Angular 2.

They provide with a set of directives that will allow us to build views by implementing native components from the device platform.

So, the first thing we want to do is to update the app.component.ts file from our todo-app project as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Component, OnInit } from "@angular/core";
import { Todo } from './sdk/models/Todo';
import { API_PROVIDERS, LoopBackConfig, TodoApi } from './sdk';

@Component({
selector: "my-app",
templateUrl: './app.component.html',
providers: [ API_PROVIDERS, TodoApi ],
})
export class AppComponent implements OnInit {

private todo: Todo = new Todo();
private list: Array<Todo> = new Array();

constructor(private ts: TodoApi) {
// Update with your API Address, IP in same network or DNS
LoopBackConfig.setBaseURL('http://192.168.0.1:3000');
LoopBackConfig.setApiVersion('api');
}

ngOnInit() {
this.getTodos();
}

addTodo(): void {
this.ts.create(this.todo).subscribe(res => {
this.todo = new Todo();
this.list.push(res);
});
}

getTodos(): void {
this.ts.find().subscribe(res => (this.list = res));
}
}

As you can see this is a standard Angular 2 Component, other than that I know I said NativeScript does not rely on the browser DOM, but then why are we calling an html file?.

They -NativeScript Team- say it is because it is better for IDE compatibility so you can have a nice mark up in every IDE, but at the end the components are not rendered in a web view, but it translates to native components.

So, here we are… by using import { TodoApi } from './sdk and by setting it in the providers configuration, Angular 2 will inject the service in the constructor, providing us to a full set of methods to communicate with the API.

If you don’t know what is an @Injectable Service please read my previous post: Angular 2: How do components communicate.

Exploring SDK (IntelliSense)

Thanks to the fact that we exported a LoopBack SDK in TypeScript we have all type of definitions that when using Visual Studio Code you will be able to explore the provided functionality by the generated sdk:

Exploring NativeScript API SDK With VCode

As you can see you got all type of methods to connect with your LoopBack Application as if you were coding for the back end, really cool.

Create Todo View

We need to create a file named app.component.html and add the following directives:

1
2
3
4
5
6
7
8
9
<StackLayout>
<TextField [(ngModel)]="todo.text" hint="Add New Todo"></TextField>
<Button text="Add" (tap)="addTodo()"></Button>
<ListView [items]="list">
<template let-item="item">
<Label [text]="item.text"></Label>
</template>
</ListView>
</StackLayout>

Basically what we are doing is to create a view with a small form that will present a TextField a Button and a ListView components to present the data we get from the API or in order to create new todos.

Clean CSS

Remove every css style from the app.component.css file.

One thing, any css you use in your components will work similar to what I explained in the html view, it will be parsed to native when compiled.

Test the App

Come on… Really? That’s all? Well Yes.. for now!!! But with no more than 50 lines of code we built a truly native application that integrates a NodeJS with NativeScript by providing an IBM StrongLoop’s LoopBack Framework Client SDK Out of the box, just like the big players, I mean.. You can now build Native Applications like a MEAN Expert.

It is time to test, so just make sure your API is up and running:

1
2
$ cd todo-api
$ node .

Open another terminal, connect your mobile device or setup a emulator and then:

1
$ tns livesync [android|ios] --watch

This command will add the platform to your project and all the required dependencies.

You should be able to see a native app with native components and should be able to start adding todos and persist these into the database.

It is not going to be a pretty app, I never promised to build the most pretty app in the world, but to show you that with less than 50 lines of code we could build an App with API integration SDK.

So.. you should see something like:

Playing with the Todo App

Hilarious

Really guys… we need to give some credit to the people who built these technologies, I mean… I know I’m the very first person integrating these so we could make such black magic, but… Together with these genius and a with great help of the community; we all have been building platforms and tools that really makes me think that the future of JavaScript is Now!!!

If you liked this super awesome tutorial and now you feel you can build native apps like an expert; please share this with your friends on Twitter, Facebook, boss, team, teachers, students, everyone need this kind of knowledge.

I really hope you enjoyed this post number 10 and if you want me to keep working on even better and more advanced tutorials, let me know.. leave a comment or tweet, I’m always willing to help :D

What is next?

In my next blog posts I want to explore more the NativeScript world, more Angular 2 and also there are much more to learn about IBM’s StrongLoop LoopBack Framework, because I mean.. we basically did not write a line of backend code lol.

If you like this series and want be aware of next releases and new packages, follow me on Twitter @johncasarrubias and if you feel it leave a comment here.

Thanks for reading.


Comments:

...