javascriptangularjsfunctionangularjs-factory

How to define multiple functions and call one function inside other function in Angular JS Factory


Can Anyone help me how to create multiple function in Angular JS Factory, And I want to access the returned value from one function and process something in another function , I have tried below but didn't succeed

In Below Function I wanted to fetch value in modifyProduct function which we get from getProduct(response.data)

I have referred below Questions but didnt get much understanding

AngularJS : From a factory, how can I call another function

Calling a function in another function with AngularJS factory

 app.factory('ProductsService', function($http) {
  function getProduct() {
    return $http.get('finalmsodetails.json').then(function(response) {
      console.log(response.data);
      return response.data;
    });
  }

  function modifyProduct() {
    this.getProduct().then(function(value) {
      console.log(value);
    });
  }
  return {
    getProduct: getProduct,
    modifyProduct: modifyProduct
  };
});

Solution

  • You're close. Just need to drop this., because you're calling another function that's defined in the local scope, not some method on an object. And i think you probably will want to have modifyProduct return the promise, so that anyone calling this function can tell when it succeeds or fails.

    function modifyProduct() {
      return getProduct().then(function(value) {
        console.log(value);
      });
    }