關注微信訂閱號:TongeBlog,可查看[ionic2項目實戰]全套教程,還有各種乾貨等著你!
這一講包含的內容有:
1.組件(Component)的基本介紹
2.定義服務組件(Service)
3.在ionic2中使用網絡請求
這個組件是應用入口,啟動時做的一些初始化一般都在這裡調用,先分析下當前代碼,請看注釋。
2.定義服務組件(Service)
2.1.定義全局配置服務
在app目錄下建一個service文件夾,存放公用服務,再新建一個ConfigService.ts組件,稱它為配置服務組件,主要配置項目中的所有api接口地址。
import {Injectable} from '@angular/core';@Injectable()export class ConfigService { private hostURL:string = "http://www.tngou.net/tnfs/api"; constructor() {} // 獲取抽屜分類 getClassify() { return this.hostURL+"/classify"; } }
2.2定義網絡請求服務新建一個app.service.ts(官方推薦這種命名)與app.ts同級目錄,內容如下。
import {Injectable, Inject} from '@angular/core';import {Http, HTTP_PROVIDERS, Response, Headers} from '@angular/http';import {ConfigService} from "./services/ConfigService";import {Observable} from 'rxjs/Observable';import 'rxjs/Rx';@Injectable()export class SexyService {// 構造函數constructor( private http: Http, private configService: ConfigService) {}// 獲取抽屜菜單getMenuItems() { let url = this.configService.getClassify(); return this.http.get(url).map( res => res.json().tngou ).catch(this.handleError);}// 處理錯誤private handleError(error: Response) { console.log(error); return Observable.throw(error.json().error || 'Server Error');}}
怎麼樣,是不是跟面向對象語言很相似?各關鍵字的解釋如下。
import 導入其他組件
class 聲明類
constructor 構造函數
Injectable() 裝飾器,通過該函數裝飾的服務,才可在組件的構造函數中依賴注入。
3.在ionic2中使用網絡請求網絡請求的服務定義好了,接下來就可以在項目中使用了,在這之前,我們先看看當前目錄結構;
接下來的工作都在app.ts應用入口組件裡,在應用初始化時,獲取抽屜菜單。
setup 1. 在app.ts頂部導入之前定義的兩個component
import {SexyService} from './app.service' import {ConfigService} from "./services/ConfigService";
setup 2. 將這兩個component加入到提供商
@Component({ templateUrl: 'build/app.html', providers: [SexyService, ConfigService]})
setup 3. 在app.ts的構造函數中依賴注入這兩個component
constructor( public platform: Platform, public menu: MenuController, public sexyService: SexyService) { }
setup 4. 應用初始化時調用SexyService的getMenuItems()獲取抽屜菜單
ngOnInit() { // 動態獲取抽屜菜單 this.sexyService.getMenuItems().subscribe(data => { this.pages = []; for (var i = 0; i < data.length; i++) { var c = data[i]; // 組織新的數據 this.pages.push({ item: { id: c.id, title: c.title }, component: ListPage }) } })}
app.html的完整代碼如下:
<ion-menu [content]="content"> <ion-toolbar> <ion-title>天狗閱圖</ion-title> </ion-toolbar> <ion-content> <ion-list> <button ion-item *ngFor="let p of pages" (click)="openPage(p)"> {{p.item.title}} </button> </ion-list> </ion-content> </ion-menu> <ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>`
在ion-item對應的有一個事件(click)="openPage(p)",可跳轉到列表頁(列表頁在第3講中實現),並傳遞一個對象,具體實現在app.ts中。
app.ts完整代碼如下:
import {Component, ViewChild} from '@angular/core';import {ionicBootstrap, Platform, MenuController, Nav} from 'ionic-angular';import {StatusBar} from 'ionic-native';import {HelloIonicPage} from './pages/hello-ionic/hello-ionic';import {ListPage} from './pages/list/list';import {SexyService} from './app.service' //導入我們的服務import {ConfigService} from "./services/ConfigService";@Component({ templateUrl: 'build/app.html', providers: [SexyService, ConfigService]})class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = HelloIonicPage; pages: Array<{ item: any, component: any }>; constructor( public platform: Platform, public menu: MenuController, public sexyService: SexyService ) { } ngOnInit() { // 動態獲取抽屜菜單 this.sexyService.getMenuItems().subscribe(data => { this.pages = []; for (var i = 0; i < data.length; i++) { var c = data[i]; // 組織新的數據 this.pages.push({ item: { id: c.id, title: c.title }, component: ListPage }) } }) } initializeApp() { this.platform.ready().then(() => { StatusBar.styleDefault(); }); } // 跳轉到ListPage頁 並傳遞一個對象 openPage(page) { this.menu.close(); this.nav.push(page.component, { item: page.item }); }}ionicBootstrap(MyApp);
OK,這時我們ionic serve試試看?注意: 在做的過程中,你可能碰到的錯誤:
Error: Can't resolve all parameters for SexyService: (?, ?).
這是因為沒有在自定義的component上增加@Injectable() 裝飾器,這玩意在C#裡叫特性,在java裡叫註解,大家理解就好。
ORIGINAL EXCEPTION: No provider for SexyService!
這個是因為沒有在@Component組件的元數據裡加入providers: [SexyService, ConfigService]提供商,這個告訴注入器如何創建我們自定義的component。
XMLHttpRequest cannot load ******. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
這個問題在ionic1項目實戰教程中提到過,基本上每個人都會遇到,chrome瀏覽器有一個跨域的插件,非常好用,這裡再給大家分享一下:Access-Control-Allow-Origin,下載地址https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related (fq)。安裝成功之後在chrome瀏覽器右上角有個開關,打開後按照如下配置即可解決跨域的問題。
第2講到這裡就結束了,如果有任何問題,歡迎在下方留言回復,或者通過以下的聯繫方式聯繫到我。
作者:Tonge
出處:微信訂閱號TongeBlog
關於作者:移動團隊負責人,喜歡分享技術,熱愛移動開發,擅長於移動端後臺構架、WebApi接口開發、原生WindowsPhone App開發、Windows Universal Platform App(通用應用程式開發)、原生iOS開發、和移動端跨平臺Ionic開發,專注於各種移動開發技術的研究。對移動端有著非常高的熱情和豐富的開發經驗,熟悉移動端的整個開發流程。
如有問題,可以通過TongeDev@live.cn 聯繫我,非常感謝。
版權申明:歡迎轉載,但必須保留此段文字註明出處,違者必究。
加群交流:[Tonge移動跨平臺開發QQ交流群] 111055535
也可通過下方的二維碼關注