AngularJS $routeProvider.resolve doubt.

84 views
Skip to first unread message

Derrick Joseph

unread,
Aug 21, 2014, 12:03:41 PM8/21/14
to kera...@googlegroups.com
I saw this example of resolve in a github repo and its working perfectly but when I tried to do the same in my app the Factory service isn't getting invoked 

App.factory('guestService', function($rootScope, $http, $q, $log) {
  $rootScope.status = 'Retrieving data...';
  var deferred = $q.defer();
  $http.get('rest/query')
  .success(function(data, status, headers, config) {
    $rootScope.guests = data;
    deferred.resolve();
    $rootScope.status = '';
  });
  return deferred.promise;
});

App.config(function($routeProvider) {
  $routeProvider.when('/', {
    controller : 'MainCtrl',
    templateUrl: '/partials/main.html',
    // refer to : API reference / ngRoute / provider / $routeProvider
    resolve    : { 'guestService': 'guestService' },
  });
  $routeProvider.when('/invite', {
    controller : 'InsertCtrl',
    templateUrl: '/partials/insert.html',
  });
  $routeProvider.when('/update/:id', {
    controller : 'UpdateCtrl',
    templateUrl: '/partials/update.html',
    resolve    : { 'guestService': 'guestService' },
  });
  $routeProvider.otherwise({
    redirectTo : '/'
  });
});

This is what I am trying to do:
FilesFetchFactory.js :
'use strict';

angular.module('udecApp').factory('FetchFileList',
['passKey','globalIV','$scope','$http','$q','$log','CryptoMan', 
function FetchFiles (passKey,globalIV,$scope,$http,$q,$log,CryptoMan){
var deferred = $q.defer();
$http.get('rest/home').success(function(data){
var files = data;
for (file in files){
file.file_name = CryptoMan.decrypt({
key : passKey,
iv  : globalIV
});
}
console.log(files);
deferred.resolve(files);
}).error(function(data,headers,config,status,statusText) {
alert('ERR');
console.log('data : ' + data);
console.log('headers : ' + headers);
console.log('config : ' + config);
console.log('status : ' + status );
console.log('statusText : ' + statusText);
});
return deferred.promise();
}
]);

app.js:

'use strict';

/**
 * @ngdoc overview
 * @name udecApp
 * @description
 * # udecApp
 *
 * Main module of the application.
 */
var udecApp = angular.module('udecApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        reslove: {
          'FetchFileList':'FetchFileList'
        },
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  }).value('passKey','0306a1f107b14a4ef1a73aa7cd96cb501e07e3fefaa0dc4fe5fa85e40cefa41d')
  .value('globalIV', '5a33ef277c4930636fcf0f83e9162807');


I also tried the methods mentioned here. Can someone tell me where am I going wrong.



vineeth nair

unread,
Aug 23, 2014, 3:52:01 AM8/23/14
to kera...@googlegroups.com
Hi Derrick nice to see to trying good stuffs

First of all in your example you where trying add to factory method FetchFileList in resolve, thats wrong .. i can give two reasons for it
 1) to call any factory method directly , u need to first inject it 
 2) U cant inject a factory or Service into Config in angularjs

Now let me try to put some basic example to explain what u can do

var app = angular.module("demoApp",[]);

app.provider('loadData', function () {  
   this.$get = function() {
       var name = this.name;
       return {
           sayHello: function() {
            console.log("Called in resolve");                 
           }
       }
   };
   this.hello = function(){
    console.log("Function Called From Resolve");
   }
});

app.config(function($routeProvider, loadDataProvider) {
$routeProvider
.when("/user/:name/:city",{
templateUrl : "tmpl_one.html",
controller : "oneCtrl",
resolve : {
loadData  : loadDataProvider.hello,    //Method defined in Provider
moreData : moreData           //Normal Function
                                        someData : function (){}                      // its also allowed and fine
}
})
.otherwise({
redirectTo : "/user/:name/:city"
})
});


var moreData = function($q,$timeout){
var defer = $q.defer();
$timeout(function(){
defer.resolve("moreData");
}, 2000);
return defer.promise;
};

The part inside $get is the same that you use in factory or service , and this part is not accessible in config, only the member defined outside it like  function hello, This is actually availble in config so that before Services are injected into controllers or other services u have the option Configure the Provider may be based on environment or other properties


Like

myApp.provider('helloWorld', function() {
    this.name = 'Default';
 
    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!"
            }
        }
    };
 
    this.setName = function(name) {
        this.name = name;
    };
});
 
//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
}); 


So Either define it as line function , normal function or call from Provider , u cant use Factory or Service in config , u use it in .run() though thats executed after config not worth to think of it in this case 




I hope u understood the stuffs  and why services should not be allowed to be injected and used in config . 

Thanks,
Vineeth


Derrick Joseph

unread,
Sep 19, 2014, 12:34:11 AM9/19/14
to kera...@googlegroups.com
For some reason my resolve isnt working and I have no idea as to what's going wrong, the boilerplate code for my angular app was generated by yeoman-angular generator.  I am trying to fetch the required resource before rendering, is there any other way to do it, other than resolve.
Reply all
Reply to author
Forward
0 new messages