如何在 AngularJS 中为 $resource 方法添加回调 [英] How to add call back for $resource methods in AngularJS

查看:16
本文介绍了如何在 AngularJS 中为 $resource 方法添加回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用户更新/创建一些数据后,我们需要向用户显示错误/成功消息可能是一种常见情况,我们如何在 AngularJS 中实现它?
我想添加回调但找不到解决方案.使用 $http.post().success().error() 有效,但我想知道我是否可以使用更高级别的 API $resource 来做到这一点.
或者,我们应该写指令还是使用 $watch()?
提前感谢您的帮助.

It could be a common case that we need to show an error/success message to the user after he updates/creates some data, how can we implement it in AngularJS?
I want to add callbacks but could not find a solution. Using $http.post().success().error() works, but I wonder if I can do it with the higher lever API $resource.
Or, we should write directives or use $watch()?
Thanks for your help in advance.

推荐答案

Resource 类中的操作可以像低级 $http 一样传递成功和错误回调服务

Actions from the Resource class can be passed success and error callbacks just like the lower level $http service

来自文档

  • HTTP GET类"操作:Resource.action([parameters], [success], [error])
  • 非 GET类"操作:Resource.action([parameters], postData, [success], [error])

非获取操作以 $ 为前缀.

Non-get actions are prefixed with $.

所以你可以这样做

User.get({userId:123}, function(u, getResponseHeaders){
  // this is get's success callback
  u.abc = true;
  u.$save(function(u, putResponseHeaders) {
    // This is $save's success callback, invoke notification from here
  });
});

<小时>

这里是 另一个来自之前 plunker 的示例.get 请求将失败,因为它请求一个不存在的 json 文件.将运行错误回调.


here's another example from a previous plunker. The get request will fail since it request a non existing json file. The error callback will be run.

someResource.get(function(data){
    console.log('success, got data: ', data);       
}, function(err){
    alert('request failed');
});

这篇关于如何在 AngularJS 中为 $resource 方法添加回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆