如何解包 angularjs 资源?

How to unwrap angularjs resource?

在 angularjs 中,$resource 模块(第三类模块)非常适合获取承诺的数据(等等)。

例如,如果 Article 是 return 一个 $resource 的工厂:

$scope.article = Article.query();

你得到了承诺。当承诺成功解决时,你会得到类似的东西:

> $scope.article;
[Resource, Resource, $promise: Object, $resolved: true]
0: Resource
1: Resource
$promise: Object
$resolved: true
length: 2
__proto__: Array[0]

太棒了!

我搜索的是是否存在一种通用方法来解开某些特殊任务的承诺。

所以,像这样:

> $resource.unwrap($scope.article);
[Array,Array]
0: Object
1: Object
length: 2
__proto__: Array[0]

注意:

I don't search to code a function to implement the unwrap method, I already did it for my needs. I am looking for a 'native' way. However I it doesn't exist and someone as already coded a robust function to make it the right way, why not !

你可能错过了some part of AngularJS documentation

You can also access the raw $http promise via the $promise property on the object returned

Article.query().$promise.then(function(articles) {
  $scope.articles = articles;
});

另一方面,AngularJS already provides method angular.toJson that removes all keys from object with $ as first character

/**
 * @ngdoc function
 * @name angular.toJson
 * @module ng
 * @kind function
 *
 * @description
 * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
 * stripped since angular uses this notation internally.
 *
 * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
 * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
 * @returns {string|undefined} JSON-ified string representing `obj`.
 */
function toJson(obj, pretty) {
  if (typeof obj === 'undefined') return undefined;
  return JSON.stringify(obj, toJsonReplacer, pretty ? '  ' : null);
}

toJsonReplacer看起来

function toJsonReplacer(key, value) {
  var val = value;

  if (typeof key === 'string' && key.charAt(0) === '$') {
    val = undefined;
  } else if (isWindow(value)) {
    val = '$WINDOW';
  } else if (value &&  document === value) {
    val = '$DOCUMENT';
  } else if (isScope(value)) {
    val = '$SCOPE';
  }

  return val;
}