2016年6月26日 星期日

Angular2 + Ionic2

最近的angular2的釋出時,不曉得大家有沒有發現ionic也推出適合 angular2,所以當然先來試用看看ionic2, 似乎ionic2 為了在手持裝置上加了不少的元件,大家再來一起研究看看吧~

一、建立ionic 2 的語法

npm install -g ionic@beta
//開啟ionic2的新專案【cutePuppyPics
ionic start cutePuppyPics –v2  

//執行ionic2
cd cutePuppyPics 
ionic serve                


建立ionic 專案 預設為tabs為範本

二、開始撰寫ionic2angular2
示範在contact.html頁面中,增加navigation (瀏覽頁面-->返回頁面)的功能

contact.html
<ion-navbar *navbar hideBackButton>
<ion-title>
Contact
</ion-title>
</ion-navbar>

<ion-content>
<ion-list>
<ion-item *ngFor="let item of items" (click)="openNavDetailsPage(item)">
<ion-thumbnail item-left>
<img src="img/{{item.image}}">
</ion-thumbnail>
<h2>{{item.title}}</h2>
<p>Hayao Miyazaki • 1988</p>
<button clear item-right>View</button>
</ion-item>
</ion-list>
</ion-content>

因為我的來源是items,所以要先設定list的範本樣式和點擊的範圍,點擊整列就能進入到下一頁,所以在<ion-item> 加了click事件,接下來就要實作clickangular 語法囉~

contact.ts
import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {ItemService} from './item_services';
import { viewItem } from './view_item';

@Component({
templateUrl: 'build/pages/contact/navigation-details.html', //呈現navigation 的下一頁面
})
class NavigationDetailsPage {
item;
constructor(params: NavParams) {
this.item = params.data.item; //傳遞過來的參數
console.log(NavParams);
}
}

@Component({
templateUrl: 'build/pages/contact/contact.html',
providers: [ItemService] //呼叫ItemSerivce, 目的抽出資料層
})
export class ContactPage {
private items;
//預設為先執行的函式,navController是預設先,作者還另外注入itemService
constructor(public nav: NavController, private itemService: ItemService) {
this.itemService.getItems().then(cItems => this.items = cItems);
}
//外部點選click事件
openNavDetailsPage(viewItem) {
this.nav.push(NavigationDetailsPage, { item: viewItem }); //將頁面轉換到navigationDetailPage
}
}

這樣就簡單的完成有導覽式navigation的行為,點選資料列,進入到下一頁後,還能返回上一頁的一連串的動作。




下次再介紹其他的控件吧~ 先簡單略過囉!


三、安裝單元測試的套件

當案件越來越龐大時,單一測試就越來越重要囉… 所以angular也有推出自已的unit test套件,所以結合ionic2 一起來試用看看…

npm install karma karma-jasmine karma-phantomjs-launcher --save-dev
npm install -g karma-cli
npm install angular-mock --save-dev
kama init my.conf.js

執行的過程…會出現一連串的詢問視窗如下所示
which framwork do you want to use?
>jasmine : 就按ENTER

do you want to use require.js?
>no: ENTER

接下來不論它問是什麼…按下ENTER 就對了… 預設為主

重點在後面…你要修改kama.config.js
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'browserify'],


// list of files / patterns to load in the browser
files: [
'node_modules/es6-shim/es6-shim.js', // TypeError: undefined is not a constructor (evaluating 'new exports.Map()')
'node_modules/reflect-metadata/Reflect.js', // 'Uncaught reflect-metadata shim is required when using class decorators'
'node_modules/zone.js/dist/zone.js', // Zone.js dependencies (Zone undefined)
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
'app/**/*.spec.ts',
{ pattern: 'node_modules/reflect-metadata/Reflect.js.map', included: false, served: true }, // 404 on the same
{ pattern: 'www/build/**/*.html', included: false },
],

// list of files to exclude
exclude: [
'node_modules/angular2/**/*_spec.js',
'node_modules/ionic-angular/**/*spec*'
],

browserify: {
debug: true,
transform: [
['browserify-istanbul', {
instrumenter: require('isparta'),
ignore: ['**/*.spec.ts', '**/*.d.ts'],
}]
],
plugin: [
['tsify']
]
},

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.ts': ['browserify']
},


// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],

// web server port
port: 9876,

// enable / disable colors in the output (reporters and logs)
colors: true,

// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,

// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,

// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}

以下的設定檔中,需要修改的部份是【files,browserify,frameworks,exclude,我也還不確認為何要這麼設定… 總之按照google大神查出來的樣本,有人是這麼設定的,就能run出測試結果囉。

修改pack.json
{
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"es6-shim": "^0.35.0",
"ionic-angular": "2.0.0-beta.9",
"ionic-native": "1.2.4",
"ionicons": "3.0.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12"
},
"devDependencies": {
"angular-mock": "^1.0.0",
"browserify": "13.0.0",
"browserify-istanbul": "2.0.0",
"del": "2.2.0",
"gulp": "3.9.1",
"gulp-watch": "4.3.5",
"ionic-gulp-browserify-typescript": "^1.1.0",
"ionic-gulp-fonts-copy": "^1.0.0",
"ionic-gulp-html-copy": "^1.0.0",
"ionic-gulp-sass-build": "^1.0.0",
"ionic-gulp-scripts-copy": "^2.0.0",
"isparta": "4.0.0",
"jasmine-core": "^2.4.1",
"karma": "^0.13.22",
"karma-browserify": "5.0.5",
"karma-chrome-launcher": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-phantomjs-launcher": "^1.0.0",
"run-sequence": "1.1.5",
"tsify": "0.16.0"
},
"name": "cutepuppypics",
"description": "cutePuppyPics: An Ionic project",
"cordovaPlugins": [
"cordova-plugin-device",
"cordova-plugin-console",
"cordova-plugin-whitelist",
"cordova-plugin-splashscreen",
"cordova-plugin-statusbar",
"ionic-plugin-keyboard"
],
"cordovaPlatforms": [],
"version": "1.0.0",
"main": "gulpfile.js",
"scripts": {
"test": "karma start karma.conf.js"
},
"author": "",
"license": "ISC"
}
相依性的【devDependencies】需要加上karma等相關套件,【scripts】加上test的相關設定

下指令>npm install //下戴相依性的套件
參考自:

四、開始撰寫測試程式
app的資料夾下新增【app.spec.ts】的檔案
app.spec.ts
import {beforeEachProviders, it, describe, expect, inject} from '@angular/core/testing';
import {ItemService} from "./pages/contact/item_services";
describe('test ItemService return', () => {
beforeEachProviders(() => [ItemService]);
it('should return kitty', inject([ItemService], (mockItem) => {
let result = mockItem.getItems();
expect(result.__zone_symbol__value[0].title).toEqual("kitty");
}
));
})
Ps:如果要顯示回傳的資料,要呼叫__zone_symbol__value的屬性

>npm test //執行測試


預期結果:


沒有留言:

張貼留言