在開發ionic2項目時,會有很多頁面和服務需要創建,如果全靠自己手動創建的話,會有很多重復的枯燥的操作要做,即增加開發時間,又影響開發效率,嚴重影響寫代碼的心情。
Ionic現在提供了一個生成器功能來為您的應用程序創建頁面和服務。 這是一個命令行的功能,在終端輸入一個命令,告訴ionic你想創建什么,然后按下回車享受三秒閑暇時光:)
能夠創建的部分(CLI v2.2.3):
- page
#command
ionic g page mypage
#result
√ Create app/pages/mypage/mypage.html
√ Create app/pages/mypage/mypage.scss
√ Create app/pages/mypage/mypage.ts
mypage.html
<!--
Generated template for the Mypage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>mypage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
</ion-content>
mypage.ts
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
/*
Generated class for the Mypage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
selector: 'page-mypage',
templateUrl: 'mypage.html'
})
export class MypagePage {
constructor(public navCtrl: NavController, public navParams: NavParams) {}
ionViewDidLoad() {
console.log('ionViewDidLoad MypagePage');
}
}
- component
#command
ionic g component myComponent
#result
√ Create app/component/my-component/my-component.html
√ Create app/component/my-component/my-component.scss
√ Create app/component/my-component/my-component.ts
my-component.ts
import { Component } from '@angular/core';
/*
Generated class for the MyComponent component.
See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
for more info on Angular 2 Components.
*/
@Component({
selector: 'my-component',
templateUrl: 'my-component.html'
})
export class MyComponentComponent {
text: string;
constructor() {
console.log('Hello MyComponent Component');
this.text = 'Hello World';
}
}
- directive
#command
ionic g directive myDirective
#result
√ Create app/components/my-directive/my-directive.ts
my-directive.ts
import { Directive } from '@angular/core';
/*
Generated class for the MyDirective directive.
See https://angular.io/docs/ts/latest/api/core/index/DirectiveMetadata-class.html
for more info on Angular 2 Directives.
*/
@Directive({
selector: '[my-directive]' // Attribute selector
})
export class MyDirective {
constructor() {
console.log('Hello MyDirective Directive');
}
}
- provider
#command
ionic g provider myProvider
#result
√ Create app/providers/my-provider.ts
my-provider.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the MyProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class MyProvider {
constructor(public http: Http) {
console.log('Hello MyProvider Provider');
}
}
以上四種形式是開發過程中最長用到的,在CLI>=3.0.0的版本中,ionic2新增了更多的服務生成器,用法基本一樣,詳見這里~