Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default $resource POST data

That might be strange but I need to specify some default POST data for my $resource using the factory method of the module.

Does anyone have an idea of how to do that in AngularJS ?

EDIT :

Well, i want to do something like this :

/**
 * Module declaration.
 * @type {Object}
 */
var services = angular.module("services", ["ngResource"]);

/**
 * Product handler service
 */
services.factory("Product", function($resource) {
    return $resource("http://someUrl", {}, {
        get   : {method: "GET", params: {productId: "-1"}},
        update: {method : "POST", params:{}, data: {someDataKey: someDataValue}}
    });
});

Where data is the default data for my future POST requests.

like image 530
Nimaen Avatar asked Jun 28 '12 07:06

Nimaen


People also ask

What is $resource in AngularJS?

Overview. A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service. Requires the ngResource module to be installed.

What is resource in Angular?

Built on the top of the $http service, Angular's $resource is a factory that lets you interact with RESTful backends easily. So, let's explore $resource and use it to implement CRUD operations in Angular.

What is Angular resource in AngularJS?

AngularJS $resource is a service that lets you access RESTful web services in a way that is more Angular-friendly. $resource takes care of serializing and deserializing data for you to focus on the application logic. Moreover, AngularJS $resource provides functions to communicate with RESTful APIs.


1 Answers

This is not really the angular way to do such a thing as you lose data consistency if you do it and it doesn't reflect in your model.

Why?

The resource factory creates the object and uses object instance data as POST. I have looked at the documentation and angular-resource.js and there doesn't seem to be a way to specify any default custom properties for the object being created by resource without modifying angular-resource.js.

What you can do is:

services.factory("Product", function($resource) {
    return $resource("http://someUrl", {}, {
        get   : {method: "GET", params: {productId: "-1"}},
        update: {method : "POST"}
    });
});

and in your controller:

$scope.product = {}; // your product data initialization stuff
$scope.product.someDataKey = 'someDataValue'; // add your default data

var product = new Product($scope.product);
product.$update();
like image 100
Bogdan Rybak Avatar answered Oct 06 '22 03:10

Bogdan Rybak