0

How do I consume a webApi in an angular js factory?

WebApi

public class WarrantyController: ApiController {
    public WarrantyViewModel Get(string c, string l, string s, string cs, string productcode, string ordercode, string overrides) {
        var response = Query(new WarrantyQuery(UserContext.CreateContext(c, l, s, cs), productcode, ordercode, overrides));
        return response.Data;
    }
}

this returns json result :

GET /api/shop/warranty/get/us/en/abc/19/productA/abc-123 HTTP/1.1

2 Answers 2

1

Angular Resource module is a really good helper to consume Rest APIs.

You can create a factory like :

angular.module('appService', ['ngResource'])
    .factory('Warranty', function($resource) {
        return $resource('/api/warranty/');
    });

Then, inject your factory into your angular application as shown below:

var app = angular.module('app', ['appService']);

Finally, you can access your factory in your controller:

app.controller('warrantyController', function($scope, Warranty) {
  $scope.warranties = Warranty.query();
});

All other CRUD operations will be automatically added into your Warranty object. For more information, you can visit ngResource Documentation

Sign up to request clarification or add additional context in comments.

Comments

0

The same way you communicate with any API, use the $http service.

With this you get HTTP verb shorthands:

// Returns a promise with warranty list as a resolved parameter
function getWarranties() {
  return $get('/api/warranty').then(function(resp) {
    return resp.data;
  });
}

Or you can use the raw $http method:

// Returns a promise with warranty list as a resolved parameter
function getWarranties() {
  return $http({
    url: '/api/warranty',
    method: 'get',
    // other options...
  }).then(function(resp) {
      return resp.data;
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.