1、创建项目:ionic start demo tabs;
2、创建一个服务:ionic g provider data-server,可以做一个保存本地存储的服务用来各个页面调用,部分截图如下:
3、在app.module.ts中引入服务:
app.module.ts:
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { Test1Page } from '../pages/test1/test1';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { DataServerProvider } from '../providers/data-server/data-server'; //自定义服务
@NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
Test1Page,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
Test1Page,
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
DataServerProvider, //自定义的服务
]
})
export class AppModule {}
自定义组件、自定义指令、自定义管道都是在imports中引入的,而自定义服务是在providers中引入的
providers/data-server/data-server.ts:
import { Injectable } from '@angular/core';
import { stringify } from '@angular/core/src/util';
@Injectable()
export class DataServerProvider {
constructor() {
console.log('Hello DataServerProvider Provider');
}
public setLocalstorage(key, value){
localStorage.setItem(key, JSON.stringify(value));
}
public getLocalstoragfe(key){
return JSON.parse(localStorage.getItem(key))
}
public removeLocalstorage(key){
localStorage.remove(key);
}
public clearLocalstorage(){
localStorage.clear();
}
}
选择在about页面中试用:
about.html:
<ion-header>
<ion-navbar>
<ion-title>
About
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div class="normal-page">
<button ion-button (click)='saveLocalStorage()'>保存本地存储</button>
<button ion-button (click)='sayLocalStorage()'>获取本地存储</button>
<button ion-button (click)='clearLocalStorage()'>清除本地存储</button>
</div>
</ion-content>
about.ts:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DataServerProvider } from '../../providers/data-server/data-server';
@Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
constructor(public navCtrl: NavController, public data: DataServerProvider) {
}
ngOnInit(){
}
sayLocalStorage(){
console.log(this.data.getLocalstoragfe('key'));
}
clearLocalStorage(){
this.data.clearLocalstorage();
}
saveLocalStorage(){
this.data.setLocalstorage('key', {item1: 1, item2: 2})
}
}
ionic serve重启服务后,先点击保存再点击查看就能看到保存的本地存储,点击清除再点击查看就发现返回null: