Techumber
Home Blog Work

Build Your First Mobile App With The NativeScript and Angular2 - Part 5

Published on July 7, 2016

We are at the end of the series. If you landed on this page out of nowhere and want to know what happened before go to Part 1.

Ok, Let’s create a simple mobile app which will search the GitHub users and list the matching users in as listview. Simple right?

The final output will look as

You can download the debug apk file from here or use the below QR code.

qr code

To download compleate source code go here

Ok, So you have created your project using tns you know how to run your application.

liveSync

Before you start codeing open your terminal form where you have the project. Enter the following command.

tns liveSync android --watch

or If you are building for IOS

tns liveSync ios--watch

If any device is attached to your PC or Mac, app will be syncronized with it otherwise it will open the Android or IOS emulator.

Codeing…

In order to do it in an angulary way, we should create angular service first.

Inside the app folder creates a new folder services where we will write all our angular services.

Since it’s a very simple app we will use this folder structure for bigger apps better use some other.

We need a GitHub service which will fetch users from GitHub API.

create github.service.ts

import { Injectable } from '@angular/core';  
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

@Injectable()
export class GitHubService {  
    username: string;
    url     : string =  `https://api.github.com/search/users?`;
    constructor(private http: Http) {
        // constructor code here..
    }
    // get users data from github api
    getUsers (username:string) {
        let url:string;
        if(!username){
            return  Observable.throw(new Error("User name query can not be empty."));
        }
        this.username = username;
        url = this.url + 'q=' + this.username;
        return this.http.get(url).map(res => res.json().items);
    }
}

It’s a very simple angular2 service. In angular2 any TypeScript class as a service. All we need to do is to add @Injectable() decorator to that service.

Our service has only one functions. getUsers is to fetch the users from GitHub API. It will return a observable.

Here we are using GitHub API https://api.github.com/search/users?q= to fetch users. For more details https://developer.github.com/v3/

GitHub service is ready. Let’s use it in main angular component. To use a service inside a component we have to import the service and pass it to the component via providers attribute.

Let’s update the app.component.ts.

import { Observable } from 'rxjs/Observable';  
import { GitHubService } from './services/github.service';

@Component({
    selector: "my-app",
    providers: [GitHubService],
    templateUrl: "app.component.html",
})
export class AppComponent  {  
    public username:string;
    public isLoading:boolean = false;
    public users:Array<Object> = [];
    // inject github services
    constructor(private github:GitHubService) {
        // constructor code here...
    }
    // onSearch Button tap
    public onSearchTap() {
        if(!this.username){
            alert("Username can not be empty!");
            return;
        }
        this.isLoading = true;
        this.github.getUsers(this.username).subscribe((users) => {
            this.users = users;
            this.isLoading = false;
        });
    }
}

Here, we have loaded GitHub service and injected it into our component. Also implemented public functions onSearchTap.

This function will use github service to fetch github user data and assign it to users variable.

Finally, update app.component.html as

<StackLayout>
    <TextField hint="Username"  [(ngModel)]="username"></TextField>
    <Button text="Search" (tap)="onSearchTap()"></Button>
    <GridLayout rows="auto, *">
        <ListView [items]="users" row="1">
            <template let-item="item" let-i="index" let-odd="odd" let-even="even">
                <StackLayout>
                    <GridLayout rows="auto,auto" columns="auto, *">
                        <Image src="{{item.avatar_url}}" row="0" col="0" rowSpan="2" width="100" height="100"></Image>
                        <Label text="{{item.login}}" row="0" col="1" class="login"></Label>
                        <StackLayout row="1" col="1" orientation="vertical">
                            <Label text="Score:"  class="score-label"></Label>
                            <Label text="{{item.score}}"  class="score"></Label>   
                        </StackLayout>
                    </GridLayout>
                </StackLayout>
            </template>
        </ListView>
        <ActivityIndicator [busy]="isLoading" [visibility]="isLoading ? 'visible' : 'collapse'" row="1" horizontalAlignment="center" verticalAlignment="center"></ActivityIndicator>
    </GridLayout>
</StackLayout>

It bit complex but it’s actually very easy.

StackLayout act as a div. What ever you put inside it will come one after another.

By click Search button it triggers onSearchTap function. Once we fetch the data from api we will assign it to users varible. Which we are using to generate list check <ListView [items]="users" row="1"> line.

Understand GridLayout by comparing it with HTML tables but little advanced.

ActivityIndicator used as a loading indicator. When user click on search it will take a while to fetch data so we have to show something right?

That’s it. With only 3 files we have created our NativeScript application.

Well done!

For more.

https://www.nativescript.org/