Ionic2 快速入门

时间:2023-03-09 18:10:13
Ionic2 快速入门

本文原创版权归 博客园 yan_xiaodi 所有,转载请自觉于篇头位置显示标明原创作者及出处,这是您对作者劳动果实的自觉尊重!!

作者:yan_xiaodi

原文:http://www.cnblogs.com/yanxiaodi/p/6060123.html

电子书:https://www.gitbook.com/book/yanxiaodi/ionic2-guide/details

3.快速上手

完成 Ionic 安装后,你可以创建第一个App了。本章内容将指导你新建一个App,添加一个页面,并且实现页面间的导航。

3.1.创建项目

打开 Node 命令行,首先 cd 到项目目录,使用 start 命令来创建一个新App:

ionic start MyIonic2Project tutorial --v2

这个命令将下载项目模板,安装 npm modules,设置 Cordova 的相关信息。

tutorial 参数的意思是下载 tutorial 模板来初始化项目,如果不指定这个参数的话,比如:

ionic start MyIonic2Project --v2

默认会使用 tabs 模板。

当然你也可以加一个 blank 参数,这样就是一个空项目。

--v2 的参数必须要加,不然会建立 v1.x 版本的项目。

如果失败,有可能会出现以下信息:

Creating Ionic app in folder E:\Workspaces\Ionic2\MyIonic2Project based on tutorial project
Downloading: https://github.com/driftyco/ionic2-app-base/archive/master.zip
[=============================] 100% 0.0s
Downloading: https://github.com/driftyco/ionic2-starter-tutorial/archive/master.zip
[=============================] 100% 0.0s
Installing npm packages...
Error with start undefined
Error Initializing app: There was an error with the spawned command: npminstall
There was an error with the spawned command: npminstall
Caught exception:
undefined
Mind letting us know? https://github.com/driftyco/ionic-cli/issues

这说明 npm 安装的时候失败了,可以 cd 到项目目录,使用之前设置过的 cnpm 命令:

E:\Workspaces\Ionic2>cd MyIonic2Project
E:\Workspaces\Ionic2\MyIonic2Project>cnpm install

直到最后输出类似以下信息:

All packages installed (319 packages installed from npm registry, use 2m, speed 37.49kB/s, json 659(4MB), tarball 1.07MB)

说明 npm modules 安装成功。

3.2.在浏览器中运行

现在 cd 到项目目录,使用 serve 命令来快速浏览项目:

E:\Workspaces\Ionic2>cd MyIonic2Project
E:\Workspaces\Ionic2\MyIonic2Project>ionic serve

接下来 CLI 会编译项目,输出类似下面的内容:

> ionic-app-base@ watch E:\Workspaces\Ionic2\MyIonic2Project
> ionic-app-scripts watch
[14:38:58] ionic-app-scripts 0.0.36
[14:38:58] watch started ...
[14:38:58] build dev started ...
[14:38:58] clean started ...
[14:38:58] clean finished in 1 ms
[14:38:58] copy started ...
[14:38:58] transpile started ...
[14:38:58] lint started ...
[14:39:17] lint finished in 18.68 s
[14:39:19] transpile finished in 21.32 s
[14:39:19] bundle started ...
[14:39:23] copy finished in 25.39 s
[14:39:49] bundle finished in 29.75 s
[14:39:49] sass started ...
[14:39:53] sass finished in 4.10 s
[14:39:53] build dev finished in 55.20 s
[14:39:54] watch ready in 55.95 s
Running live reload server: http://localhost:35729
Watching: www/**/*, !www/lib/**/*
√ Running dev server: http://localhost:8100
Ionic server commands, enter:
restart or r to restart the client app from the root
goto or g and a url to have the app navigate to the given url
consolelogs or c to enable/disable console log output
serverlogs or s to enable/disable server log output
quit or q to shutdown the server and exit
ionic $

接着浏览器会打开一个地址为 http://localhost:8100 的窗口,端口号根据当前PC的实际情况可能会有变化,如果8100被占用了会使用8101等。

你可以看到运行效果: Ionic2 快速入门

3.3.项目结构

现在来看一下一个 Ionic 2 App 的结构。这是一个标准的 Cordova 项目结构。

./src/index.html

./src/index.html 是App的主要入口,设置脚本和CSS,运行整个App。我们不会花费太多时间在这个文件上,你可以看到HTML代码里有一个 <ion-app> 标签,像下面这样:

<ion-app></ion-app>

在底部还有以下的脚本:

<script src="cordova.js"></script>
<script src="build/main.js"></script>

build/main.js是自动生成的,实际上是把TypeScript转成了普通的JavaScript

cordova.js在本地开发的时候在浏览器中浏览会报404错误,这个文件会在Cordova打包的时候自动加到项目里。

./src/

src目录里我们会找到原始的没有经过编译的代码,这也是我们的主要工作目录。当我们运行ionic serve命令的时候,在src/目录下的文件会被转译成正确的浏览器能够解释的JavaScript版本(当前是ES5)。这意味着我们可以使用高级的TypeScript,但是会编译回浏览器需要的老版本的JavaScript。 src/app/app.module.ts是App的入口。

在文件底部我们会看到以下的代码:

@NgModule({
declarations: [MyApp,HelloIonicPage, ItemDetailsPage, ListPage],
imports: [IonicModule.forRoot(MyApp)],
bootstrap: [IonicApp],
entryComponents: [MyApp,HelloIonicPage,ItemDetailsPage,ListPage],
providers: []
})
export class AppModule {}

每个App都有一个root module来控制应用中其他的部分。如果你用过Ionic1Angular1的话,有点类似ng-app。这也是我们使用ionicBootstrap来启动应用的地方。

./src/app/app.html

src/app/app.html是主要的模板文件:

<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Pages</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item *ngFor="let p of pages" (click)="openPage(p)">
{{p.title}}
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

在这个模板中,我们使用了ion-menu来作为菜单,使用ion-nav组件当做主要的内容区域。ion-menu[content]属性被绑定到ion-nav的本地变量content上,所以它能够知道要显示什么。

下面我们来看如何来创建新页面并实现基本的导航。

3.4.添加页面

现在我们对Ionic 2 App的布局有了一个基本的认识,继续来实现添加和导航页面的功能。

看一下src/app/app.html,在底部会看到以下代码:

<ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

注意root属性的绑定。对于ion-nav组件来说,这是第一个或者说是“根”页面。当ion-nav组件载入时,组件引用的rootPage变量将会作为根页面被载入。

src/app/app.component.ts,MyApp组件在构造函数里指定了这个变量:

...
import {HelloIonicPage} from '../pages/hello-ionic/hello-ionic';
... export class MyApp {
... // make HelloIonicPage the root (or first) page
rootPage: any = HelloIonicPage;
pages: Array<{title: string, component: any}>; constructor(
private platform: Platform,
private menu: MenuController
) {
...
}
... }

我们看到rootPage被设置为HelloIonicPage,所以HelloIonicPage将是nav controller第一个载入的页面。

创建一个页面

接下来,我们看一下我们导入的HelloIonicPage页面。在src/pages/hello-ionic/目录下,打开hello-ionic.ts

你可以注意到每个页面都有自己的目录,每个目录中都可以看到具有相同名字的.html.scss文件。例如在hello-ionic/目录我们可以看到有hello-ionic.tshello-ionic.html, 和hello-ionic.scss。虽然这种模式不是必须的,但这有助于项目文件的良好组织。

接下来我们看到HelloIonicPage这个类。这个类创建了一个Page,即Angular中的Component(组件),并且会载入Ionic的导航系统。注意因为Page是被动态载入的,所以他们不需要selector

import {Component} from '@angular/core';

@Component({
templateUrl: 'build/pages/hello-ionic/hello-ionic.html'
}) export class HelloIonicPage {}

所有的Page都是一个类,并且关联到对应的模板文件上。看一下src/pages/hello-ionic/hello-ionic.html,即这个页面的模板文件:

<ion-header>
<ion-navbar>
<button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Hello Ionic</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding class="getting-started">
<h3>Welcome to your first Ionic app!</h3>
<p>
This starter project is our way of helping you get a functional app running in record time.
</p>
<p>
Follow along on the tutorial section of the Ionic docs!
</p>
<p>
<button primary menuToggle>Toggle Menu</button>
</p>
</ion-content>

<ion-navbar>navigation bar的模板。当我们导航到页面时,navigation bar的按钮和页面标题将会作为整个页面动画的一部分展现出来。

模板其余的部分是标准的Ionic代码,设置了内容区域和输出我们的欢迎信息。

创建一个新页面

创建这个新页面,我们并不需要做很多配置,只需要确保设置好navigation bar要展示的标题就可以了。

看一下src/pages/list/list.ts的内容,这里定义了一个新页面:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ItemDetailsPage } from '../item-details/item-details'; @Component({
templateUrl: 'list.html'
})
export class ListPage { selectedItem: any; icons: string[]; items: Array<{title: string, note: string, icon: string}>; constructor(public navCtrl: NavController, public navParams: NavParams) {
// If we navigated to this page, we will have an item available as a nav param
this.selectedItem = navParams.get('item');
this.icons = ['flask', 'wifi', 'beer', 'football', 'basketball', 'paper-plane', 'american-football', 'boat', 'bluetooth', 'build']; this.items = [];
for(let i = 1; i < 11; i++) {
this.items.push({
title: 'Item ' + i,
note: 'This is item #' + i,
icon: this.icons[Math.floor(Math.random() * this.icons.length)]
});
}
} itemTapped(event, item) {
this.navCtrl.push(ItemDetailsPage, {
item: item
});
}}

这个页面将会创建一个基本的列表页面,包含一些数字。

大致上这个页面跟我们之前看的HelloIonicPage非常类似。接下来我们看一下如何导航到这个新页面。

3.5.导航到页面

回忆一下上个章节,我们在ListPage类里有一些下面的代码:

itemTapped(event, item) {
this.navCtrl.push(ItemDetailsPage, {
item: item
});
}

你也许注意到我们引用了ItemDetailPage。我们用以下的代码将其importapp/pages/list/list.ts里:

import {ItemDetailsPage} from '../item-details/item-details';

当保存文件后,ionic serve进程会自动重新编译以应用新的更改,并自动刷新浏览器。重新看一下浏览器中的页面,当点击一个项时,它将会导航到详情页面。注意菜单按钮被一个返回按钮代替了,这是Ionic遵循的一种原生App的导航方式,当然这是可以被配置的。

工作原理

Ionic 2的导航像一个简单的栈,我们使用push方法来导航到新页面,将其放在栈的顶部,并显示一个返回按钮。对于返回,我们使用pop方法将其从栈中移除。因为我们在构造函数中设置了this.navCtrl属性,我们可以调用this.navCtrl.push()方法,来导航到一个新的页面。我们还可以将一个object传递给将要导航过去的页面。使用push方法导航到新页面非常简单,但Ionic的导航系统是非常灵活的。可以从导航文档处获得更详细的导航示例。

对于UrlIonic 2Ionic 1是不同的。我们要确保我们可以返回到某个Page,所以一般不使用Url来进行导航。当然我们在必要的时候还是有办法来使用Url导航的。

接下来

你已经掌握了Ionic 2的入门知识。你可以继续学习Ionic 2的各种Component,和关于硬件的Native APIs