Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Yeoman generated Angular app works fine til I add ['ngResource'] and then it hangs

I created an AngularJS app with "yo angular", ran "grunt server --force" and got to the 'Allo, Allo' success screen.

When I added ['ngResource'] as shown below it appears to hang...or at least nothing is displayed in the browser any more.

We're tried adding $resource as a param to function..i.e. tried actually using a resource but no luck. I don't see any errors in the web console. We verified that angular-resource.js is listed in components/angular-resources.

This feels like a dumb newbie error but its got us stuck.

'use strict';
angular.module('a3App', ['ngResource'])
  .factory('myService', function () {
  var foo = 42;
  return {
    someMethod: function() {
       return foo;
    }
   };
});
like image 567
Brian Tarbox Avatar asked Apr 29 '13 17:04

Brian Tarbox


2 Answers

Got the answer (or at least the understanding) from Green & Seshadri's AngularJS book.

The angular.module statement works in two modes: configuration and run. The 'ngResource' statement works fine with configuration:

angular.module('a3App', ['ngResource']).config(function ($routeProvider) {
  $routeProvider
    .when('/', {
     templateUrl: 'views/main.html',
     controller: 'MainCtrl'
   })
   .otherwise({
     redirectTo: '/'
   });
});

Works

but put that same statement in an angular.module(...).factory statement and it fails/quietly hangs (because .factory is a run rather than configuration statement):

angular.module('a3App', ['ngResource']).factory('myService', function($resource) {
...

This is explained at location 6456 of the Kindle version of the AngularJS book ("Loading and Dependencies" in Chapter 7). It makes sense after the fact (I guess all things do)..but an error message and/or updated documentation would be great.

like image 74
Brian Tarbox Avatar answered Oct 23 '22 16:10

Brian Tarbox


Brian, I experienced the same thing. My AngJS app would quietly hang whenever I included ['ngResource'] in a factory.

I fixed this problem by changing this code:

angular.module('a3App', ['ngResource']).factory('myService', function($resource) {
...

Into this:

angular.module('a3App').factory('myService', function($resource) {
...

And my application still worked fine in consuming a json rest api.

like image 44
Kurt Mueller Avatar answered Oct 23 '22 14:10

Kurt Mueller