侧边栏壁纸
博主头像
微笑涛声

一个在编程学习中逐渐变强的孩子! 热爱编程,喜欢软件开发!

  • 累计撰写 131 篇文章
  • 累计创建 63 个标签
  • 累计收到 7 条评论
隐藏侧边栏

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

微笑涛声
2020-04-21 / 0 评论 / 0 点赞 / 375 阅读 / 1,976 字
温馨提示:
本文最后更新于 2021-06-16,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

新建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、演示效果

image

0

评论