Build Your First Mobile App With Ionic 2 & Angular 2 - Part 5


http://gonehybrid.com/build-your-first-mobile-app-with-ionic-2-angular-2-part-5/


23 February 2016 on Ionic 2, Angular 2, TypeScript | 48 Comments

Now that we have the introductions out of the way (see Part 3 and Part 4), let's go ahead and create a simple Ionic 2 app that connects to a REST API, gets some data from it and displays it in a view.

This tutorial is for Ionic 2, you can find the Ionic 1.x tutorial here.

This tutorial is part of a multi-part series:
Part 1 - Introduction to Hybrid Mobile Apps
Part 2 - Set Up your Development Environment
Part 3 - Introduction to TypeScript & ES6
Part 4 - Introduction to Angular 2
Part 5 - Build an Ionic 2 App (this post)
Part 6 - Navigating between Pages
Part 7 - Test on Emulators and Mobile Devices

The source code can be found on GitHub.


What are we going to build?

We are going to build a page that takes a GitHub username and displays the GitHub repositories for that user.

App Screenshot

Create Ionic project

In Part 2 we installed the Ionic CLI and we'll use that to create our Ionic 2 project.

$ ionic start ionic2-tutorial-github blank --v2 --ts

The name of our project is ionic2-tutorial-github based on the blank Ionic template. Since we will be using TypeScript, we specify that we to use the TypeScript template by adding the argument --ts. We also need to add the argument --v2 to create an Ionic 2 project, if you leave that out it will default to Ionic 1.

For more information on how to use the Ionic CLI, type the ionic --help command or check out the documentation.

Now you should have a new folder ionic2-tutorial-github with the Ionic project files inside it.

$ cd ionic2-tutorial-github

Let's see if we can launch our Ionic 2 app in the browser. It will just display a "Hello World" card for now since we haven't actually built anything yet.

We'll use the Ionic CLI again to spin up a local web server and open a browser to display the app:

$ ionic serve

Update March 8: The Ionic team are currently changing the build configuration on the starter templates to use Gulp, so if you're getting any errors with ionic serve, read this or check the comments below for a solution.

Hello World Screenshot

This command supports live-reload, so when you make changes to the code it will instantly update the browser.

Testing the app in the desktop browser first will make your life so much easier since you can easily debug it. We'll have a look at how to test on a mobile device later. (Or check out this post from the old Ionic 1 tutorial.)

Inside the project

If you're using Visual Studio Code you can type in the following command to open the folder in the editor:

$ code .

This will work automatically on Windows after the Visual Studio Code installation, but for OS X you need to set it up to work from the terminal.

Let's have a look at the files and folders that have been created in our project:

app This folder will contain all the code you're going to write for the app, ie. the pages and services.
hooks This folder contains scripts that can be executed as part of the Cordova build process. This is useful if you need to customize anything when you're building the app packages.
node_modules Ionic projects use npm to import modules, you'll find all imported modules here.
resources This folder contains the icon and splash images for the different mobile platforms.
typings This folder contains type definition files for external modules that are not written in TypeScript.
www This folder contains the index.html, remember all the app code should be in the app folder, not in the www folder.
config.xml This file contains the configuration for Cordova to use when creating the app packages.
ionic.config.js Configuration used by the Ionic CLI when excuting commands.
package.json This file contains the list of all npm packages that have been installed for this project.
tsconfig.json Configuration for the TypeScript compiler.
webpack.config.js This file contains the configuration for WebPack, which will create a bundle from the modules in the app.

Building the app

We'll start with creating a service that will get the data from the GitHub API. This service will then be injected into our Home page component.

Create a services folder in the app folder and add the file github.ts containing the following code.

Update April 8: The Ionic CLI can now generate the service based on a TypeScript template with the ionic generate command. See documentation on how to use it.

Creating the service

import {Injectable} from 'angular2/core';  
import {Http, Headers} from 'angular2/http';

@Injectable()
export class GitHubService {  
    constructor(private http: Http) {
    }

    getRepos(username) {
        let repos = this.http.get(`https://api.github.com/users/${username}/repos`);
        return repos;
    }
}

As you can see we're importing a couple of Angular 2 modules into this service. We need to add the @Injectable decorator to let Angular know that this service can be injected into another module and we need Http to call the GitHub API.

Want to know more about @Injectable? Read Angular 2 Injectables.

The Http module uses RxJS to return Observables which is different from Angular 1's $http service that returns Promises. I recommend you read this excellent guide to understand Observables: The introduction to Reactive Programming you’ve been missing.

Please note that you can use another library or vanilla JavaScript to connect to the GitHub API, you don't need to use Angular's Http module.

Creating the page

Now let's build the page that will display the list of repositories. In the directory app/pages/ there is a home directory that has 3 files in it:

home.html This is the template for the Home page, it contains all the html code.
home.scss This file contains the styles for the Home page.
home.ts This file contains the TypeScript code for the Home page.

In home.ts we'll write the code to get the list of repositories from the GitHubService and populate the foundRepos property.

import {Page} from 'ionic-angular';  
import {GitHubService} from '../../services/github';

@Page({
    templateUrl: 'build/pages/home/home.html',
    providers: [GitHubService]
})
export class HomePage {  
    public foundRepos;
    public username;

    constructor(private github: GitHubService) {
    }

    getRepos() {
        this.github.getRepos(this.username).subscribe(
            data => {
                this.foundRepos = data.json();
            },
            err => console.error(err),
            () => console.log('getRepos completed')
        );
    }
}

Instead of the default Angular 2 @Component decorator, Ionic uses it's own decorator @Page. We tell it where to find the template for the page and in the providers section we define an array of injectable services. In this case we only have one: GitHubService.

As I mentioned before, we are using an Observable to return the data from the service. To get the actual data, we use the subscribe method and pass in 3 functions: one to handle the data that is returned, one to handle errors, and one method that will be called when the Observable has completed without errors.

In home.html we'll define the template for the page:

<ion-navbar *navbar>  
    <ion-title>
        GitHub
    </ion-title>
</ion-navbar>

<ion-content class="home">  
    <ion-list inset>
        <ion-item>
            <ion-label>Username</ion-label>
            <ion-input [(ngModel)]="username" type="text"></ion-input>
        </ion-item>
    </ion-list>
    <div padding>
        <button block (click)="getRepos()">Search</button>
    </div>
    <ion-card *ngFor="#repo of foundRepos">
        <ion-card-header>
            {{ repo.name }}
        </ion-card-header>
        <ion-card-content>
            {{ repo.description }}
        </ion-card-content>
    </ion-card>
</ion-content>  

As you can see the code contains all kinds of different <ion- elements. These are all components in the Ionic framework that have some styling and behaviour attached to them. Depending on which mobile platform the code is running on these components will look and behave a bit differently.

We're using data binding expressions to bind the input field to the username property and to invoke the getRepos() function when the user clicks the button.

We're using the *ngFor binding to loop through the list of foundRepos and create an <ion-card> element for each repository.

Check out the documentation for an overview of all the components Ionic has to offer.

Testing the app

You should now be able to load the app in the browser again and it should return a list of repositories for the username you typed in.

$ ionic serve --lab

I like to use the --lab option to display both the iOS and Android layout at the same time.

App Screenshot

The source code can be found on GitHub.


What's Next?

So now you've seen a very simple implementation for an Ionic 2 app, but you probably want to build an app that has more than 1 page, so in Part 6 we'll have a look at navigating between pages.

Follow me on Twitter @ashteya and sign up for my weekly emails to get new tutorials.

If you found this article useful, could you hit the share buttons so that others can benefit from it, too? Thanks!




posted @ 2016-05-22 09:11  张同光  阅读(118)  评论(0编辑  收藏  举报