Ionic step by step (1)

时间:2022-04-30 13:29:39

刚接触 ionic,一步一步学习,有错误的,望大家指出。

Ionic step by step (1)

公式

Ionic = Cordova + Angular2 + ionic CSS

Cordova: 提供了使用 JavaScript 调用 Native 功能

安装

  • 全局安装 ionic 和 cordova
npm install -g cordova ionic
  • android,需安装 JDK 和 androidSDK、Gradle,并配置好环境变量

新建 ANDROID_HOME 变量名,并设置其值为 androidSDK 目录

Ionic step by step (1)

在 Path 中添加 platform-tools 目录路径和 tools目录路径

Ionic step by step (1)

在 Path 中添加 bin 目录路径

Ionic step by step (1)

提示:这些都是跟后面打包android有关的,还有就是项目的路径里最好不要包括中文,会打包出错。

创建应用

ionic start myApp tabs

myApp: 项目名

tabs: 模板(默认tabs,还有其他的模板,如sidemenu)

遇到问题

  • Error: connect ETIMEOUT 192.30.255.121:443
  • 解决(使用vpn*吧
ionic start myApp tabs --skip-npm
(我用的时候好像也没用,不会跳过npm install,所以不用加--skip-npm,到npm install时,手动停止,并进行cnpm install)
  • 运行时需要下载安装 @ionic/cli-plugin-ionic-angular
  • 解决
cnpm install --save-dev @ionic/cli-plugin-ionic-angular

知识点

  • ionic -h

    查看帮助

  • ionic info

    查看当前 Ionic 相关的环境变量

  • ionic cordova platform add ios

    添加 ios 项目

  • ionic cordova build ios

    同步到 ios 项目

  • ionic cordova emulate ios

    运行项目 apk

  • ionci cordova platform add android

    添加 android 项目

  • ionic cordova build android

    同步到 android 项目

  • ionic cordova emulate android

    运行项目 apk

创建登录页面

ionic g page Login
<!--
Generated template for the LoginPage page. See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header no-border> <ion-navbar transparent>
<!-- <ion-title>登录</ion-title> -->
</ion-navbar> </ion-header> <ion-content>
<ion-slides pager="false" autoplay="2000" loop="true" speed="1500" effect="fade">
<ion-slide class="slide-background swiper-no-swiping" *ngFor="let background of backgrounds" [ngStyle]="{'background-image': 'url(' + background +')'}"></ion-slide>
</ion-slides>
<div class="login-container">
<!-- logo -->
![](assets/logo/cat_logo.png)
<form [formGroup]="form" (ngSubmit)="login(form)">
<ion-item [ngClass]="{'has-invalid': form.controls.username.value && form.controls.username.invalid, 'has-valid': form.controls.username.value && form.controls.username.valid}">
<ion-label floating>手机号/邮箱</ion-label>
<ion-input type="text" name="username" formControlName="username"></ion-input>
</ion-item> <ion-item [ngClass]="{'has-invalid': form.controls.password.value && form.controls.password.invalid, 'has-valid': form.controls.password.value && form.controls.password.valid}">
<ion-label floating>密码</ion-label>
<ion-input type="password" name="password" formControlName="password"></ion-input>
</ion-item> <ion-item no-lines>
<ion-label text-right>记住密码</ion-label>
<ion-toggle name="remember" formControlName="remember" checked="false"></ion-toggle>
</ion-item> <div class="login-div">
<button ion-button class="login-btn" type="submit" [disabled]="!form.valid">登录</button>
</div>
<p (click)="openResetPassword()"><strong>忘记密码?</strong></p>
</form>
</div>
</ion-content>

这里不用angular2自带的验证类(ng-valid 和 ng-invalid)的原因是存在延迟

  • login.ts
import { Component, Inject } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { NavController, NavParams, ModalController, LoadingController } from 'ionic-angular';
// 页面
import { TabsPage } from '../tabs/tabs'; /**
* Generated class for the LoginPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/ @Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage { public form: FormGroup;
public backgrounds: Array<string> = [
'assets/backgroundImages/background-4.jpg',
'assets/backgroundImages/background-5.jpg',
'assets/backgroundImages/background-6.jpg',
'assets/backgroundImages/background-7.jpg',
]; constructor(
@Inject(FormBuilder) fb: FormBuilder,
public navCtrl: NavController,
public navParams: NavParams,
public modalCtrl: ModalController,
public loadingCtrl: LoadingController,
) {
this.form = fb.group({
// 账号,手机或邮箱
username: ['', Validators.compose([Validators.required, Validators.pattern(/(^1(3[0-9]|4[57]|5[012356789]|7[01678]|8[0-9])\d{8}$)|(^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$)/)])],
password: ['', Validators.compose([Validators.required, Validators.pattern(/^\w{6,16}$/)])],
remember: false,
});
} ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
} // 重置
openResetPassword() {
console.log('Reset password clicked');
} // 登录
login(form) {
this.presentLoading();
console.log(form.value);
setTimeout(() => {
// 页面跳转,可带数据
let tabs = this.modalCtrl.create(TabsPage);
tabs.present();
}, 3000);
} // 模拟等待
presentLoading() {
let loader = this.loadingCtrl.create({
content: '登录中,请稍后...',
duration: 3000
});
loader.present();
} }

使用 Storage

  • 确保安装了所需的依赖包,没有则安装
cnpm install --save @ionic/storage
  • 在 app.module.ts 引入
import { IonicStorageModule  } from '@ionic/storage';

// 此处省略一小段代码

@NgModule({
declarations: [
MyApp,
...pages,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot(),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
...pages,
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
  • 在需要用到的组件中注入
import { Storage } from '@ionic/storage';
// 省略
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage { public form: FormGroup; constructor(
@Inject(FormBuilder) fb: FormBuilder,
public storage: Storage,
public navCtrl: NavController,
public navParams: NavParams,
public modalCtrl: ModalController,
public loadingCtrl: LoadingController,
) {
this.form = fb.group({
// 账号,手机或邮箱
username: ['', Validators.compose([Validators.required, Validators.pattern(/(^1(3[0-9]|4[57]|5[012356789]|7[01678]|8[0-9])\d{8}$)|(^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$)/)])],
password: ['', Validators.compose([Validators.required, Validators.pattern(/^\w{6,16}$/)])],
remember: false,
});
} ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
// 确保 storage
this.storage.ready().then(() => {
this.storage.get('userInfo').then((value) => {
if ( !value ) { return; }
let userInfo = JSON.parse(value);
this.form.setValue({
username: userInfo.username,
password: userInfo.password,
remember: userInfo.remember,
});
});
});
} // 重置
openResetPassword() {
console.log('Reset password clicked');
} // 登录
login(form) {
if ( form.value.remember ) {
const userInfo: Object = {
username: form.value.username,
password: form.value.password,
remember: form.value.remember,
};
this.storage.ready().then(() => {
this.storage.set('userInfo', JSON.stringify(userInfo));
});
}
this.presentLoading();
console.log(form.value);
setTimeout(() => {
let tabs = this.modalCtrl.create(TabsPage);
tabs.present();
}, 3000);
} // 模拟等待
presentLoading() {
let loader = this.loadingCtrl.create({
content: '登录中,请稍后...',
duration: 3000
});
loader.present();
} }

修改主题

app 主题样式表:src/theme/variables.scss

  • 颜色
$colors: (
primary: #488aff,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222,
twitter: #55acee, /* 自定义颜色 */
);

注意:在此定义会增加到所有组件中,即会增加 css文件的大小,从而会减低app速度。

  • 更进一步定义,基本色和对比色
$colors: (
primary: #488aff,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222,
twitter: (
base: #55acee,
contrast: #666,
),
);