Bolboa Bolboa - 2 months ago 7
AngularJS Question

Angular's factory method not being called

In my

services.js
file I have the following
$resource
to connect to my RestAPI...

app.factory('Profile', function ($resource) {
console.log("here");
var Bear = $resource('http://192.168.0.11:3000/api/bears/:id', {id:'@id'});
Bear.save({name:"Yogi"});
});


Now, I am trying to test whether it is working, but
console.log("here");
is never reached.

This is my
app.js
file containing my controller...

var app = angular.module('starter',
[
'ionic',
'ngResource'
]
);

app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);

}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
});


As you can see I included
ngResource
but still the factory method is not called. What am I doing wrong?

Answer

As @Phil mentioned, your factory is just sitting there doing nothing because:

  1. It isn't injected into any controller or service. (or in your case the app.run block)

Solution: Inject it into the app.run block next to $ionicPlatform

  1. The Profile factory should be called from the app.run block using a method called saveBear.

Solution: Change the code in services.js to this:

app.factory('Profile', function ($resource) {
    var saveBear = function(){
      console.log("here");
      var Bear = $resource('http://192.168.0.11:3000/api/bears/:id',{id:'@id'});
      Bear.save({name:"Yogi"});
    }

  return {
    saveBear: saveBear
  }

});

Then call the method in the run block using the statement

Profile.saveBear();

Comments