新建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、在需要的地方引用

  • 构造方法​​constructor()​​中引入
,private toastController: ToastController
,private toastservice:ToastService
  • 具体实现方法加入
this.toastservice.showSuccessToast("成功信息");
this.toastservice.showErrrorToast("错误信息");
this.toastservice.showWarningToast("警告信息");

4、举个栗子:

  • 逻辑部分代码(ts文件)
presentToastByService1(){
this.toastservice.showSuccessToast("成功");
}
presentToastByService2(){
this.toastservice.showErrrorToast("错误");
}
presentToastByService3(){
this.toastservice.showWarningToast("警告");
}
  • HTML部分代码
<ion-button (click)="presentToastByService1()">成功信息测试</ion-button>
<ion-button (click)="presentToastByService2()">错误信息测试</ion-button>
<ion-button (click)="presentToastByService3()">警告信息测试</ion-button>

5、演示效果

移动端开发:ionic集成toast消息提示插件_java