Search code examples
javascriptangularjsfactoryplunker

Angularjs: Achieve Same Structure for Service as Factory


I am playing with angularjs services and factories. I have created a factory called BookFactory as follows:

// Code goes here

app
  .factory('BootFactory', function() {
    var bookFactory;

    function add() {

    }

    function remove() {

    }

    function getAll() {

    }
    bookFactory = {
      add: add,
      remove: remove,
      getAll: getAll
    }
    return bookFactory;

  });

And a BookService as follows:

app.service('BookService', function() {

        var bookService;

        function add() {

        }

        function remove() {

        }

        function getAll() {

        }

        /*
        It throws:
        Uncaught ReferenceError: Invalid left-hand side in assignment.

        How can I achieve the same structure with the services which I have used in factories.

        this = {
          add: add,
          remove: remove,
          getAll: getAll
        };

        */

        //Do I have to add all methods like this
        this.add=add;
        this.remove=remove;
        this.getAll=getgAll;

        //Or there's any other better way to achieve it

      });

What I want to do is I want to keep the keep the structure consistent i.e. I want want something like this for both factory and services:

bookFactory = {
          add: add,
          remove: remove,
          getAll: getAll
        }

In case of factory it works fine. But in case of service I can not do so. cause service works with this and I can not do this:

/*
            It throws:
            Uncaught ReferenceError: Invalid left-hand side in assignment.

            How can I achieve the same structure with the services which I have used in factories.

            this = {
              add: add,
              remove: remove,
              getAll: getAll
            };

            */

What I am thinking to do is:

//Do I have to add all methods like this
            this.add=add;
            this.remove=remove;
            this.getAll=getgAll;

            //Or there's any other better way to achieve it

Is there any better way to do so? Here's the plunkr.


Solution

  • You can create bookService like as-

    app.service('BookService', function() {
        return {
              add:add,
              remove:remove,
              getAll:getAll
            };
    
        function add() {
    
            }
    
            function remove() {
    
            }
    
            function getAll() {
    
            }
    
      });