Search code examples
javascriptangularjsangularjs-servicepouchdb

Error with PouchDB: TypeError: angular.factory is not a function


I'm trying to figure out how to use PouchDB in AngularJS. I'm trying to follow these instructions https://github.com/wspringer/angular-pouchdb

I think I'm having a problem understanding the syntax for creating factories and/or services. I get as far as the section on "Interacting with the database"

app.js

'use strict';

angular
  .module('myappApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute',
    'pouchdb'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
angular.factory('someservice', function(pouchdb) {
  // Do something with pouchdb.
  var db = pouchdb.create('testdb');
  pouchdb.destroy('testdb');
  db.put({_id: 'foo', name: 'bar'});
});

When I add the "db.put", The message I see in the browser's console is:

 [15:17:45.343] TypeError: angular.factory is not a function @ http://127.0.0.1:9000/scripts/app.js:21

Solution

  • The angular object does not have a factory method, so it will returned as undefined.

    Try putting it on the object returned by the module method.

    angular
      .module('myappApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngRoute',
        'pouchdb'
      ])
      .config(function ($routeProvider) {
        $routeProvider
          .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
          })
          .otherwise({
            redirectTo: '/'
          });
      })
      // note the difference here, it is using the object returned by module() and config()
      .factory('someservice', function(pouchdb) {
        // Do something with pouchdb.
        var db = pouchdb.create('testdb');
        pouchdb.destroy('testdb');
        db.put({_id: 'foo', name: 'bar'});
      });