prabug
prabug

Reputation: 161

How to invoke a Asp.Net Web API 2.0 http batch request using Angular?

I created a sample web api in Asp.Net Web Api 2.0 with Http batch support. http://blogs.msdn.com/b/webdev/archive/2013/11/01/introducing-batch-support-in-web-api-and-web-api-odata.aspx describes the example.

How could I invoke this batch API using Angular?

Upvotes: 3

Views: 1724

Answers (1)

Jon
Jon

Reputation: 4295

I know this is a bit of a late answer but I have create a angular module to enable HTTP batch requests. The module is here https://github.com/jonsamwell/angular-http-batcher and I have written a blog post about it here http://jonsamwell.com/batching-http-requests-in-angular/.

The module is transparent to the developer so once you have included it and setup a batch endpoint all calls to that service will be batched automatically. Let me know if you need any help getting started with it.

For example the below 3 http request will be automatically batched and turned into a single request!

var app = angular.module('httpBatchExample', ['jcs.angular-http-batch']);

app.config([  
    'httpBatchConfigProvider',
    function (httpBatchConfigProvider) {
        // setup some configuration to tell the module that requests to 
        // 'https://api.myapp.com' can be batched and send the batch request to https://api.myapp.com/batch
        httpBatchConfigProvider.setAllowedBatchEndpoint(
            'https://api.myapp.com',
            'https://api.myapp.com/batch');
    }
]);

app.controller('mainCtrl', [  
    '$scope',
    '$http',
    function ($scope, $http) {
        // Get the data as normal which will automatically be turned into a single HTTP request
        $http.get('https://api.myapp.com/products').then(function (data) {
            console.log('success 0 - ' + data.data);
        }, function (err) {
            console.log('error 0 - ' + err);
        });

        $http.get('https://api.myapp.com/products/2').then(function (data) {
            console.log('success 1 - ' + data.data);
        }, function (err) {
            console.log('error 1 - ' + err);
        });

        $http.put('https://api.myapp.com/products', {
            Name: 'Product X',
            StockQuantity: 300
        }).then(function (data) {
            console.log('success 2 - ' + data.data);
        }, function (err) {
            console.log('error 2 - ' + angular.fromJson(err));
        });
    }]);

Upvotes: 3

Related Questions