新建toast.service文件进行方法封装
1、新建文件命令
ionic g service service/toast
2、toast.service完整代码
import { Injectable } from '@angular/core';
import {ToastController} from "@ionic/angular";
@Injectable({
providedIn: 'root'
})
export class ToastService {
//构造方法注入ToastController
constructor(private toastController: ToastController) { }
//成功提示信息
public async showSuccessToast(msg:string){
const toast = await this.toastController.create({
message: msg,
duration: 4000, //持续出现的时间(毫秒)
color:"success",
position:"middle" //在窗口的显示位置
});
toast.present();
}
//警告提示信息
public async showWarningToast(msg:string){
const toast = await this.toastController.create({
message: msg,
duration: 4000, //持续出现的时间(毫秒)
color:"warning",
position:"middle" //在窗口的显示位置
});
toast.present();
}
//警错误提示信息
public async showErrrorToast(msg:string){
const toast = await this.toastController.create({
message: msg,
duration: 4000, //持续出现的时间(毫秒)
color:"danger",
position:"middle" //在窗口的显示位置
});
toast.present();
}
}
3、在需要的地方引用
,private toastController: ToastController
,private toastservice:ToastService
this.toastservice.showSuccessToast("成功信息");
this.toastservice.showErrrorToast("错误信息");
this.toastservice.showWarningToast("警告信息");
4、举个栗子:
presentToastByService1(){
this.toastservice.showSuccessToast("成功");
}
presentToastByService2(){
this.toastservice.showErrrorToast("错误");
}
presentToastByService3(){
this.toastservice.showWarningToast("警告");
}
<ion-button (click)="presentToastByService1()">成功信息测试</ion-button>
<ion-button (click)="presentToastByService2()">错误信息测试</ion-button>
<ion-button (click)="presentToastByService3()">警告信息测试</ion-button>
5、演示效果
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。