Search code examples
javascriptangularjsangular-resource

How to unwrap angularjs resource?


In angularjs, the $resource module (third type module) is awesome to fetch promised data (and so more).

for example if Article is a factory that return a $resource :

$scope.article = Article.query();

and you get a promise. When the promise is successfuly resolved, you get something like that:

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

Great !

What I search is if exists a common method to unwrap the promise for some special tasks.

So, something like this :

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

NB :

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 !


Solution

  • You probably miss 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;
    });
    

    In the other hand, 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);
    }
    

    and toJsonReplacer looks

    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;
    }