Angular custom module - "object function(){...} foo has no method 'bar'"

243 views Asked by At

I'm trying to create a custom wrapper for $http in angular. Here's the code outline:

angular.module('jotted_resource', ['ng'])
.factory('jotted_resource', ['$http', 'communicationStatus',
    function($http, cs) {
        function jResourceFactory(url){
            function jResource(value){
                var self = this;
                this.query = function(callback){
                    var value = [];
                    return $http.get(url).then(function(response){
                        var data = response.data;
                        for(var i in data){
                            value.push(new jResource(data[i]))
                        }
                    });
                    return value;
                }
            }
            return jResource;

        }
        return jResourceFactory;
    }
]); 

But example code like this:

app.factory("label", ["jotted_resource", function(jotted_resource) {
   var label = jotted_resource("api/labels");
   var all = label.query();
   ...

Throws an error saying:

TypeError: Object function jResource(value){ ...} has no method 'query'

I'm afraid that my knowledge on all the complexities of JavaScript's objects/functions/prototypes isn't sufficient enough to wrap my head around this issue. Please point out how can I fix the code.

1

There are 1 answers

0
zs2020 On

This is a pure JavaScript issue. Since label is a function and you need to use the new keyword to create an object in order to make prototype inheritance work.

var all = (new label()).query();