Pregunta

I am trying to make resource calls to multiple endpoints with the same instantiated object. Methods that use a prototype resource method do change the endpoint, but the @id fails to extract. id is for sure a property on the object, if i do a regular model.$get, it works. I appreciate any help, i'm hoping the comments in the code will better help explain.

admin.controller('ModelController', ['$scope', 'Model', function($scope, Model) {

    // first call to instantiate the models with the default resource url
    Model.query(
        {},
        function(resp) {
            $scope.models = resp.results;
        }
    );

    // this event is emited from a directive
    // data is a object from the models collection
    $scope.$on('modelClick', function(event, data) {

        // without this, event fires twice, i am not sure why.
        event.stopPropagation();


        // creates model with resource prototype
        // the hope is then to be able to do $get or $save on $scope.model
        $scope.model = new Model(data);


        // call below will work normal, pulls the id out of the object
        // and sends it with the request to the default url
        $scope.model.$get();


        // this method changes the resource url to the correct one
        // but id=undefined is put on the query string
        // i have debugged the resource api and when this gets called
        // the object is being sent to the $parse method and the id is available
        $scope.model.getInfo();


        // updates the view
        $scope.$apply('model');
    });


}]);


admin.factory( 'Model', ['$resource', function($resource) {

    // default resource url
    var Model = $resource('/:url', {id: '@id', url: 'initial/path'}, {});


    // method to call a different endpoint, but with same id from instantiated object
    Model.prototype.getInfo = function(params, success, error) {
        var response = this.$get(
            {url: 'info/path'}
        );
        return response;
    };

    return Model;

}]);

Any help with why $scope.model.getInfo() calls /info/path?id=undefined would be greatly appreciated. Thank you.

¿Fue útil?

Solución

I'm not sure, if this will work, but can you try this,

Model.prototype.getInfo = function(params, success, error) {
       var id = this.id; // if id is not a direct member of 'this'. Please inspect the 'this' for any getter method to get the member variables.
        var response = this.$get(
            {url: 'info/path', 'id':id}
        );
        return response;
    };

It could be really hard to put this code in the comment section, so added as an answer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top