priyanka.sarkar
priyanka.sarkar

Reputation: 26498

Not able to invoke the API Services when something is between Controller and Service in AngularJS?

I have Product.js file where

var productOPS = {

    GetProduct: function () {            

        var promiseGet = getProducts();       
    }};

Now I want to invoke ProductService.js

app.service('crudService', function ($http) {

    ///product GET

    this.getProducts = function () {
        return $http.get("/api/ProductsAPI");
    }

    ///end product    

});

And ProductController.js is

app.controller('crudController', function ($scope, crudService) {

    GetProducts();

    //Function to load all Employee records
    function GetProducts()
    {

        productOPS.GetProduct();
    } } });

How can I invoke the Service from GetProduct of Products.js and pass the value back to ProductController

Error: getProducts() is not defined.

Upvotes: 0

Views: 19

Answers (1)

maurycy
maurycy

Reputation: 8465

service should return object

app.service('crudService', function ($http) {
    return {
      getProducts: function () {
          return $http.get("/api/ProductsAPI");
        }
});

and then in controller you can sue it like this:

app.controller('crudController', function ($scope, crudService) {
  crudService.getProducts().then( function(response){
    $scope.products = response.data
  });
});

$http returns promise that's why I used then but you can do success or whatever you want

Upvotes: 1

Related Questions