Angularjs用不同的url调用实例化的资源方法

Angularjs calling instantiated resource methods with different url

本文关键字:实例化 资源 方法 调用 url Angularjs      更新时间:2023-09-26

我试图用相同的实例化对象对多个端点进行资源调用。使用原型资源方法的方法确实会更改端点,但是@id无法提取。Id肯定是对象的属性,如果我做常规模型。$get,它工作。我很感谢任何帮助,我希望代码中的注释能更好地帮助解释。

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

为什么$scope.model.getInfo()调用/info/path?Id =undefined将非常感谢。谢谢你。

我不确定,如果这将工作,但你可以试试这个,

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

将这段代码放在注释部分可能真的很难,所以作为答案添加。