Rolando
Rolando

Reputation: 62626

How to have a $resource return sample data in angular?

Assume I have a angular service with the resource:

var res = $resource('/myurl/:index', {index: '@index'})

Is there a way for me to make it such that I can define arbirary paths such that when within my service I call:

$res.query()

I can get some hardcoded output of "[1,2,3]" without having the resource actually calling the server or expecting the server to have a function that supports the query()?

Upvotes: 1

Views: 731

Answers (3)

Kevin Stone
Kevin Stone

Reputation: 8981

I think you're approaching this a bit wrong. $resource is a factory for creating Services where you specify the url and other parameters for a given API endpoint. If you have a fake or test API endpoint, just create a fake Service that returns the hard coded data.

Here's an example:

.factory('TestDataResource', function() {

    return {
        query: function() {

            // Return Hard-coded data
            return [1, 2, 3];
        }
    }
});

And then you can use it in your controllers or wherever, for example:

.controller('MyController', function($scope, TestDataResource) {

    $scope.data = TestDataResource.query();
    // $scope.data should contain [1, 2, 3]
});

Upvotes: 1

HasanAboShally
HasanAboShally

Reputation: 18675

You may use a JSON file for the sample-data.

Upvotes: 1

Andyrooger
Andyrooger

Reputation: 6746

$resource calls $http under the covers so you should be able to use $httpBackend to mock responses. This page has a wealth on information on this.

Upvotes: 0

Related Questions