我如何从一个资源$空回应? [英] How do I get a null response from a $resource?

查看:110
本文介绍了我如何从一个资源$空回应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从一个资源$一个空的反应?

How do I get a null response from a $resource?

我运行这样的:

angular.module("services").factory('Member', function($resource) {
  var Member = $resource('/api/v1/member.json');

  Member.current = Member.get();

  return Member;
});

但服务器与响应:

But the server is responding with:

null

由于用户没有登录。

但是,当我登录的结果我得到这样的:

But when I log the result I get this:

Resource
  0: "n"
  1: "u"
  2: "l"
  3: "l"
  $promise: Object
  $resolved: true
  __proto__: Resource

在哪里,因为我本来预计从字面上

推荐答案

$ resource.get 方法,默认情况下,预计JSON响应是一个对象(解析时)。
打电话时 $ resource.get(),结果将是$资源的一个实例。

$resource.get method, by default, expects the JSON response to be an object (when parsed). When calling $resource.get(), the result is going to be an instance of the $resource.

在你的榜样,呼吁 Member.get({ID:1})会产生被调用的<$c$c>new会员() 然后人口 (XHR时完成)与解析的JSON响应的特性:

In your example, calling Member.get({id:1}) will produce a $resource instance that is created by calling new Member() source and then populated source (when XHR is completed) with properties of the parsed JSON response:

shallowClearAndCopy(data, value);

与你的成员实例填充函数的签名如下:

The signature of the function with which your Member instance is populated is as follows:

function shallowClearAndCopy(src, dst) {
  dst = dst || {};

  angular.forEach(dst, function(value, key){
    delete dst[key];
  });

  for (var key in src) {
    if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') {
      dst[key] = src[key];
    }
  }

  return dst;
}

扫视函数体中,你会发现该功能并不期望的src 参数是在SRC(VAR关键别的什么,只是对象( ){... )。所以,如果你为它提供字符串的结果将是:

Glancing the function body you will realise that the function does not expect src parameter to be anything else but object (for (var key in src) { ...). So, if you provide it with string "null" the result will be:

{1: "n", 2: "u", 3: "l", ...}


ngResource内置支持使用JSON一个REST风格的API作为隐含的数据传送格式,因此,你将不能够使用诸如响应或任何否则这不是一个有效的JSON。


ngResource is built to support a RESTfull API with JSON as an implied data transfer format, hence you won't be able to use responses such as "null" or anything else which isn't a valid JSON.



除非

除非你使用的<一个href=\"http://$c$c.angularjs.org/1.2.0/docs/api/ngResource.%24resource\"><$c$c>transformResponse转换来像 {'空':真正} 飞:

app.factory('Member', function($resource) {
  var Member = $resource('member.txt', {}, {
    get: {
      method: 'GET',
      isArray: false,
      transformResponse: function(data, headersGetter){
        if(data === 'null'){
          return {null: true};
        }
        return angular.fromJson(data);
      }
    }
  });
  return Member;
});

$scope.member = Member.get({id: 1});
console.log($scope.member); // --> {null: true}

演示

DEMO

这篇关于我如何从一个资源$空回应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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