1. 程式人生 > >[轉]ionic3項目實戰教程三(創建provider、http請求、圖文列表、滑動列表)

[轉]ionic3項目實戰教程三(創建provider、http請求、圖文列表、滑動列表)

獲取 The cto avatar 設置 ddd ctp itl promise

本文轉自:https://blog.csdn.net/lyt_angularjs/article/details/81145468

版權聲明:本文為博主原創文章,轉載請註明出處。謝謝! https://blog.csdn.net/lyt_angularjs/article/details/81145468
前言:
- 從別人的博客中獲取知識,將知識寫成博客留與後來人。
- 寫博客既是對知識的總結梳理,也方便以後需要用的時候隨時來查看。

一、創建provider
1.ionic g provider storage 創建了一個名為storage的服務在src/providers裏;會自動添加到app.module.ts中。

2.先來豐富一下這個服務吧

//storage.ts
import { Injectable } from ‘@angular/core‘;

@Injectable()
export class StorageProvider {

constructor() {
console.log(‘Hello StorageProvider Provider‘);
}
public setItem(key,value){
localStorage.setItem(key,JSON.stringify(value))
}
public getItem(key){
return JSON.parse(localStorage.getItem(key))

}
public removeItem(key){
localStorage.removeItem(key)
}
}

3.接下來開始使用了

//home.html
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<h2>{{msg}}</h2>
<button ion-button class="btn-login" color="secondary" *ngIf="!isLogin" (click)="goLoginPage()">去登錄頁面</button>

<button ion-button class="btn-login" *ngIf="isLogin" (click)="logout()">退出登錄</button>
</ion-content>

//html.ts
import { Component } from ‘@angular/core‘;
import { NavController } from ‘ionic-angular‘;
import { LoginPage } from "../login/login";//引入頁面
import { StorageProvider } from "../../providers/storage/storage";//引入服務

@Component({
selector: ‘page-home‘,
templateUrl: ‘home.html‘
})
export class HomePage {
msg:string;//提示信息
isLogin:boolean=false;//是否登錄
constructor(
public navCtrl: NavController,
public storage:StorageProvider,
) {
this.init();
}
init(){
//判斷是否登錄
this.isLogin=this.storage.getItem(‘isLogin‘);
let account=this.storage.getItem(‘account‘);
if(account){
this.msg=`歡迎你,${account}`;
}else{
this.msg=`還沒登錄呢,大兄弟。`;
}
}
goLoginPage(){
this.navCtrl.push(LoginPage);//路由跳轉-前進
}
logout(){
//刪除localStorage裏面的登錄信息
this.storage.removeItem(‘isLogin‘);
this.storage.removeItem(‘account‘);
this.init();
}
}

//login.ts
import { Component } from ‘@angular/core‘;
import { IonicPage, NavController, NavParams } from ‘ionic-angular‘;
import { TabsPage } from "../tabs/tabs";
import { StorageProvider } from "../../providers/storage/storage"

//定義接口格式
interface User {
account: string;
password:string;
}

@IonicPage()
@Component({
selector: ‘page-login‘,
templateUrl: ‘login.html‘,
})
export class LoginPage {
user:User={
account:‘admin‘,
password:undefined,
}
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public storage:StorageProvider
) {
}
login(){
//設置登錄狀態為已登錄
this.storage.setItem(‘isLogin‘,true);
this.storage.setItem(‘account‘,this.user.account);
//設置某個頁面為app的路由根頁面,從此以後不能再後退頁面
//左上角的<返回沒有了,在手機上後退也不行了
this.navCtrl.setRoot(TabsPage);
}
goBack(){
this.navCtrl.pop();//路由跳轉-後退
}
}

結果如圖:


4.點擊登錄,結果如圖:

5.點擊退出登錄,又回到第一張圖片了

二、http請求、圖文列表
ionic g provider api 在src/providers/api中
在api.ts中寫get和post請求
import { Http,Headers,Response } from ‘@angular/http‘;
import { Injectable } from ‘@angular/core‘;

@Injectable()
export class ApiProvider {
//定義post請求需要的頭部
public headers=new Headers({‘Content-Type‘:‘application/json‘});
constructor(public http: Http) {
console.log(‘Hello ApiProvider Provider‘);
}
//實例get請求
public getList(){
return new Promise((resolve, reject) => {
this.http.get(‘https://jsonplaceholder.typicode.com/albums/1/photos‘)
.subscribe((res:Response)=>{
resolve(res.json())
},err=>{
console.dir(err)
reject()
});
});
}
//實例post請求
public postData(data){
return new Promise((resolve, reject) => {
this.http.post(‘https://jsonplaceholder.typicode.com/posts‘,data,{headers:this.headers})
.subscribe((res:Response)=>{
resolve(res.json())
},err=>{
console.dir(err)
reject()
});
});
}

}

3.在home.ts中引入api服務並調用get和post請求

import { Component } from ‘@angular/core‘;
import { NavController } from ‘ionic-angular‘;
import { LoginPage } from "../login/login";//引入頁面
import { StorageProvider } from "../../providers/storage/storage";//引入服務
import { ApiProvider } from "../../providers/api/api";//引入服務

//定義圖片格式接口
interface Photo {
albumId: number;
id:number;
title:string;
url:string;
thumbnailUrl:string;
}
@Component({
selector: ‘page-home‘,
templateUrl: ‘home.html‘
})
export class HomePage {
msg:string;//提示信息
isLogin:boolean=false;//是否登錄
list:Array<Photo>=[];
constructor(
public navCtrl: NavController,
public storage:StorageProvider,
public api:ApiProvider
) {
this.init();
}
init(){
//判斷是否登錄
this.isLogin=this.storage.getItem(‘isLogin‘);
let account=this.storage.getItem(‘account‘);
if(account){
this.msg=`歡迎你,${account}`;
this.getList();
}else{
this.msg=`還沒登錄呢,大兄弟。`;
}
}
getList(){
//獲取list用於顯示
this.api.getList().then(data=>{
console.dir(data);
this.list=<any>data;
});
//測試post請求
let data=JSON.stringify({
title: ‘foo‘,
body: ‘bar‘,
userId: 1
});
this.api.postData(data).then(data=>{
console.dir(data);
});
}
goLoginPage(){
this.navCtrl.push(LoginPage);//路由跳轉-前進
}
logout(){
//刪除localStorage裏面的登錄信息
this.storage.removeItem(‘isLogin‘);
this.storage.removeItem(‘account‘);
this.init();
}
}

4.在home.html中以圖文列表格式顯示

<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<h2>{{msg}}</h2>
<button ion-button class="btn-login" color="secondary" *ngIf="!isLogin" (click)="goLoginPage()">去登錄頁面</button>
<button ion-button class="btn-login" *ngIf="isLogin" (click)="logout()">退出登錄</button>
<ion-list>
<ion-item *ngFor="let item of list">
<ion-avatar item-left>
<img [src]="item?.url">
</ion-avatar>
<h2>{{item?.title}}</h2>
<p>{{item?.url}}</p>
<button ion-button clear item-right>查看詳情</button>
</ion-item>
</ion-list>
</ion-content>

5.結果如圖:


三、滑動列表
1.修改contact.ts和contact.html

//contact.ts
import { Component } from ‘@angular/core‘;
import { NavController } from ‘ionic-angular‘;

//定義學生格式接口
interface Student {
id: number;
name:string;
describe:string;
src:string;
}
@Component({
selector: ‘page-contact‘,
templateUrl: ‘contact.html‘
})
export class ContactPage {
public classList:Array<Student>=[
{id:1,name:‘aaa‘,describe:‘aaaaaa‘,src:‘assets/imgs/a1.jpg‘},
{id:2,name:‘bbb‘,describe:‘bbbbbb‘,src:‘assets/imgs/a2.jpg‘},
{id:3,name:‘ccc‘,describe:‘cccccc‘,src:‘assets/imgs/a3.jpg‘},
{id:4,name:‘ddd‘,describe:‘dddddd‘,src:‘assets/imgs/a4.jpg‘},
{id:5,name:‘eee‘,describe:‘eeeeee‘,src:‘assets/imgs/a5.jpg‘},
];
constructor(public navCtrl: NavController) {

}

}

//contact.html
<ion-header>
<ion-navbar>
<ion-title>
Contact
</ion-title>
</ion-navbar>
</ion-header>

<ion-content>
<ion-list>
<ion-item-sliding *ngFor="let item of classList">
<ion-item>
<ion-thumbnail item-start>
<img [src]="item?.src">
</ion-thumbnail>
<h2>{{item?.name}}</h2>
<p>{{item?.describe}}</p>
</ion-item>
<ion-item-options side="left">
<button ion-button color="primary">
<ion-icon name="text"></ion-icon>
Text
</button>
<button ion-button color="secondary">
<ion-icon name="call"></ion-icon>
Call
</button>
</ion-item-options>
<ion-item-options side="right">
<button ion-button color="danger">
<ion-icon name="mail"></ion-icon>
Email
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>

2.效果如圖所示

---------------------
作者:漫疏狂
來源:CSDN
原文:https://blog.csdn.net/lyt_angularjs/article/details/81145468?utm_source=copy
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

[轉]ionic3項目實戰教程三(創建provider、http請求、圖文列表、滑動列表)