天天看點

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

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

10 March 2016 on Ionic 2, Angular 2, TypeScript | 8 Comments

In this part, we'll continue with the code from the previous part and allow the user to tap on a repository in the list. The app will then navigate to a details page and display the contents of the repo's README file.

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

Part 6 - Navigating between Pages (this post)

Part 7 - Test on Emulators and Mobile Devices

The source code can be found on GitHub.

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

We are already using navigation...

Before we start writing any code, I want to point out that we are actually already using navigation in the app to load

HomePage

.

Have a look in your

app.ts

file and you'll see the following lines of code:

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {} 
})
export class MyApp {  
  rootPage: Type = HomePage;
                

The app.ts file is the starting point for the app and as you can see it's template contains an

<ion-nav>

element. This is a navigation controller and we'll use it, later on, to navigate between the pages.

The

rootPage

is set to

HomePage

, so the navigation controller knows which page to load when the app is launched. You can obviously change this to any page you have within the app.

Now it's time to write the code for navigating to the details page.

Modify HomePage

Let's start by adding a click handler in home.html for the repo items.

<ion-card *ngFor="#repo of foundRepos" (click)="goToDetails(repo)">  
           

We'll need to import

NavController

in home.ts.

import {Page, NavController} from 'ionic-framework/ionic';  
import {DetailsPage} from '../details/details';  
                

We're also importing

DetailsPage

, but we haven't actually built that yet, so you'll probably see an error in your editor, but just ignore that for now.

Next, inject the NavController into the constructor.

constructor(private github: GitHubService,  
            private nav: NavController) {
}
                

And add the

goToDetails

function to handle the click and instruct it to navigate to the

DetailsPage

.

goToDetails(repo) {  
    this.nav.push(DetailsPage, { repo: repo });
}
                

OK, that was easy, right? Let's take a step back to understand the way navigation works in Ionic.

The

NavController

already has the first page loaded:

HomePage

and to navigate to

DetailsPage

, we

push

it onto the navigation stack and the framework will take care of loading the page and displaying the view transitions that are unique to the mobile platform.

We can use the

pop

function to take

DetailsPage

out of the navigation stack, the navigation controller will then go back to

HomePage

.

We don't need to explicitly use the

pop

function if

DetailsPage

has an

<ion-navbar>

because the framework will put a Back button in the navigation bar. When the user taps this button, the

pop

will be automatically executed.

We also want

DetailsPage

to know which repo was selected by the user, so we are sending the

repo

as a parameter and later on we'll see how to retrieve it on

DetailsPage

.

Add new function to GithubService

We'll add the

getDetails

function to

GitHubService

, so we can call that when we're creating

DetailsPage

.

getDetails(repo) {  
    let headers = new Headers();
    headers.append('Accept','application/vnd.github.VERSION.html');

    return this.http.get(`${repo.url}/readme`, { headers: headers });
}
                

The code above will get the contents of the repo's README file. We're adding the

Accept

header to specify that we want the README in HTML format, so we can easily display it on the

DetailsPage

.

Create DetailsPage

Go into the apps/pages folder in the project and add a new folder details.

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

Create the file details.html and add the following code:

<ion-navbar *navbar>  
    <ion-title>
        {{ repo.name }}
    </ion-title>
</ion-navbar>

<ion-content>  
    <div padding [innerHTML]="readme"></div>
</ion-content>  
           

As you can see we're using a different type of binding for displaying the README contents. We can not use the code below because that will encode the HTML code and we'll end up seeing the code itself on the view.

What we want is to add the contents of the README file as HTML to the DOM, and we can do that by binding the

innerHTML

property on the

<div>

to

readme

.

Create the file details.ts and add the following code:

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

@Page({
    templateUrl: 'build/pages/details/details.html',
    providers: [GitHubService]
})
export class DetailsPage {  
    public readme = '';
    public repo;

    constructor(private github: GitHubService, 
                private nav: NavController, 
                private navParams: NavParams) {

        this.repo = navParams.get('repo');

        this.github.getDetails(this.repo).subscribe(
            data => this.readme = data.text(),
            err => {
                if (err.status == 404) {
                    this.readme = 'This repo does not have a README. :(';
                } else {
                    console.error(err);
                }
            },
            () => console.log('getDetails completed')
        );
    }
}
                

This page is quite similar to

HomePage

, except now we're also importing the

NavParams

module. We need that to get the parameter

repo

that was sent by

HomePage

.

We're Done!

Fire up the browser with

ionic serve

and you should be able to tap on a repository and see the contents of the README file.

Build Your First Mobile App With Ionic 2 &amp; Angular 2 - Part 6

The source code can be found on GitHub.

Navigating with Tabs and Menus

So now you know how to navigate from one page to another, what about navigating with Tabs and Menus? These are actually not hard to implement and the Ionic documentation has examples for both here: Tabs and Menus.

What's Next?

In the next part we'll conclude this tutorial series by exploring how to deploy and test on emulators and mobile devices.

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!

繼續閱讀