restangular icon indicating copy to clipboard operation
restangular copied to clipboard

Restangular.copy fails with collection because angular thinks the collection is an array and calls push on it.

Open hickscorp opened this issue 11 years ago • 2 comments

Hi everyone,

i'd like to know if the dev team is aware of something that i believe is a bug in Restangular (Probably in Angular, but it makes Restangular unusable for me).

Let's say i have the following caching code:

      # This is inside a service class i use.
      cacheStore:       {}
      cache:            (obj) ->
        store             = @cacheStore[obj.route]||={}
        if store[obj.id]?
          @Restangular.copy obj, store[obj.id] unless store[obj.id]==obj
        else
          store[obj.id] = obj
        obj
      cacheCollection:  (objs) ->
        if @cacheStore[objs.route]?
         unless @cacheStore[objs.route]==objs
           @Restangular.copy objs, @cacheStore[objs.route]
        else
          @cacheStore[objs.route] = objs
        objs

Then i use it like this for single-instance models:

        @Restangular.addElementTransformer 'events', false, (model) =>
          @cache model

This basically calls the @cache method every time an element needs comes from the server. This way, if the same element is being retrieved at different locations of the code, always the same instance of the model is being returned. This works great.

Now let's say i do the same for collections:

    @Restangular.addElementTransformer 'events', true, (models) =>
      @cacheCollection models

Then Restangular crashes the second time the collection is retrieved, because of a problem in Angular, with the error "TypeError: undefined is not a function". i have debugged a little bit, and i have figured that this is originating from "function copyRestangularizedElement(fromElement, toElement)", at some point it is calling "var copiedElement = angular.copy(fromElement, toElement);". Angular is in turn trying to copy the resource, and does a test on it ("if (isArray(source)) {") which is successful (While the collections isn't really an array), so it tries to then copy stuff using the "push" method on the object ("destination.push(result);") which fails.

i would really like to be able to copy a Restangular collection "in-place" in another (Because this way controllers or other objects that have a reference to it will keep the same reference). How could i work around this please?

Thanks, Pierre.

hickscorp avatar Sep 26 '14 18:09 hickscorp

Bump, any feedback on this? Is this project still alive?

hickscorp avatar Nov 18 '15 09:11 hickscorp

mgonto has left as the primary author of Restangular (see #1319), so the issues and PRs have gotten a bit out of hand. Can you provide a live example on Plunkr please?

daviesgeek avatar Jun 18 '16 00:06 daviesgeek