[转]ionic3项目实战教程三(创建provider、http请求、图文列表、滑动列表)

时间:2022-10-20 08:54:54

本文转自: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
版权声明:本文为博主原创文章,转载请附上博文链接!