5

私は例に従いましたが、カスタム メソッドをリソースのプロトタイプに追加するときに何か問題があるようです。

app.factory('Product',function ($resource,$cacheFactory) {
        var Product = $resource('/the/url/:id', {id: '@id'}),
            cache = $cacheFactory('Product'),
            products;
        Product.prototype.all = function(){
            products = cache.get('all');
            if(typeof products == 'undefined'){
                products = Product.query();
                cache.put('all',products);
            }
            return products;
        };
        return Product;
    })

コントローラーで私はします$scope.products = Product.all();が、私は得ます

TypeError: Object function Resource(value) {
    copy(value || {}, this);
} has no method 'all'
4

2 に答える 2

3

実際にはまだインスタンスを持っていないためだと思います。これを行う必要があります:

$scope.products = new Product();
// now you can run the all function
$scope.products.all()

もう 1 つのオプションは、サービス レベルで all() メソッドを定義することです。new Product() の後にのみ使用できるプロトタイプに追加する代わりに、次のように変更できます。

app.factory('Product',function ($resource,$cacheFactory) {
    var Product = $resource('/the/url/:id', {id: '@id'}),
        cache = $cacheFactory('Product'),
        products;
    Product.all = function(){
        products = cache.get('all');
        if(typeof products == 'undefined'){
            products = Product.query();
            cache.put('all',products);
        }
        return products;
    };
    Product.prototype.$all = function () {
        Product.all.call(this);
    }
    return Product;
})

このようにして、リソースに Product.all() があり、インスタンスに product.$all() があります。

于 2013-03-04T15:07:48.980 に答える