Reputation: 4671
I'm new in Angular, and I'm trying to understand the basic My Project is like Mean.
My router.js
router.get('/', function (req, res, next) {
res.render('index', {});
});
my Angularfile.js
var app = angular.module('ibApp', ['ngRoute','ui.router']);
app.config([
'$stateProvider',
'$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url: '/',
resolve: {
foo: [function () {
console.log('inside')
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
app.controller("MyCtrl",['$scope',function($scope) {
console.log("here!");
}]);
my index.html
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-route.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="/javascripts/angularApp.js"></script>
But when I get the / (index) route, I haven't console.log('inside'), but I have only console.log("here");
I tried also http://localhost:3000/#/
, but my problem persist.
Upvotes: 0
Views: 669
Reputation: 22323
The Resolve provider is not executing the function in your case. The function itself is being returned as the dependency object, because the function is never invoked. If the function is invoked, the return value of the function is treated as the dependency.
try:
resolve: {
foo: [function () {
console.log('inside')
}()]
}
note the ()
at the end of the function declaration to invoke the function.
You can also return the function with a name, and invoke the function inside the controller.
Note that the reason this is occurring is because foo
is not being provided the function as the resolve object (which would implicitly execute the function and assign the result to foo
), rather foo
is declared as an array, and the function is simply foo[0]
. You could also invoke the function as foo[0]
in the controller.
Based on your comments, you are trying to execute a service function and return the result. In this case, you should ensure the service is available to the module, and then simply invoke it. It is not necessary to try to inject the service into your resolve function the way you might with a controller declaration.
i.e. instead of doing :
resolve: {
postPromise: ['users', function (users) {
console.dir('here '+users);
return users.getAll();
}]
you can do:
app.config([
'$interpolateProvider',
'$stateProvider',
'$urlRouterProvider',
'users',
function ($interpolateProvider, $stateProvider, $urlRouterProvider, users) {
...
resolve: {
allTheUsers: function (users) {
console.dir('here '+users);
return users.getAll();
}
http://plnkr.co/edit/FOgVgz5kvfuzPAAgtsVC?p=preview
Upvotes: 2