You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AngularJS中根据API响应显示toastr提示

设备添加与编辑功能的Toastr提示实现

需求:我正在我的应用中实现设备的添加与编辑功能,希望能够根据API的响应结果显示toastr提示。

原始代码片段:

angular.module("myApp", ['ui.bootstrap', 'toastr']).controller("myController", function ($scope, $http, $uibModal, toastr, $timeout) {


    if (newName) {
        $http.post('/api/Device/AddDevice', { name: newName })
            .then(function () {
                toastr.success("Device added","Sucess")
                $http.get('/api/Device/GetAllDevices')
                    .then(function (response) {
                        $scope.devices = response.data;
                    })
                    .catch(function (error) {
                        console.error('Error fetching devices:', error);
                    });
            })
}

完善后的实现方案

针对需求,补充API请求失败时的Toastr错误提示,同时添加设备编辑功能的对应逻辑,确保所有操作结果都能通过Toastr反馈给用户:

angular.module("myApp", ['ui.bootstrap', 'toastr']).controller("myController", function ($scope, $http, $uibModal, toastr, $timeout) {

    // 提取复用函数:获取设备列表
    const fetchDevices = () => {
        $http.get('/api/Device/GetAllDevices')
            .then(function (response) {
                $scope.devices = response.data;
            })
            .catch(function (error) {
                toastr.error('获取设备列表失败', '错误');
                console.error('Error fetching devices:', error);
            });
    };

    // 页面初始化加载设备列表
    fetchDevices();

    // 添加设备功能
    $scope.addDevice = function(newName) {
        if (!newName) {
            toastr.warning('请输入设备名称', '提示');
            return;
        }
        $http.post('/api/Device/AddDevice', { name: newName })
            .then(function () {
                toastr.success('设备添加成功', '成功');
                fetchDevices(); // 刷新设备列表
                $scope.newName = ''; // 清空输入框
            })
            .catch(function(error) {
                // 优先使用API返回的自定义错误信息,否则用默认提示
                const errorMsg = error.data?.message || '设备添加失败,请稍后重试';
                toastr.error(errorMsg, '错误');
                console.error('Error adding device:', error);
            });
    };

    // 编辑设备功能
    $scope.editDevice = function(deviceId, newName) {
        if (!newName) {
            toastr.warning('请输入新的设备名称', '提示');
            return;
        }
        $http.put(`/api/Device/EditDevice/${deviceId}`, { name: newName })
            .then(function () {
                toastr.success('设备编辑成功', '成功');
                fetchDevices(); // 刷新设备列表
            })
            .catch(function(error) {
                const errorMsg = error.data?.message || '设备编辑失败,请稍后重试';
                toastr.error(errorMsg, '错误');
                console.error('Error editing device:', error);
            });
    };
});

关键优化点

  • 提取fetchDevices复用函数,减少重复代码
  • 为添加/编辑操作的失败场景添加Toastr错误提示,支持API返回的自定义错误信息
  • 增加输入合法性校验,用Toastr提示用户补全必要信息
  • 编辑功能遵循RESTful规范使用PUT请求
  • 操作成功后清空输入框,优化用户操作体验

内容的提问来源于stack exchange,提问作者J.trytocode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:03:26