I've created a service which checks the user login state (log the user in if token exists, otherwise redirect to login page).
Originally I called this service through the routeProvider resolve - this works perfectly once, but since Angularjs services are singleton the test would not run for consecutive calls.
I then tried to move the test into a method within the returned object, but I can't seem to be bale to get the routeProvider resolve to call a specific method of a service (which makes sense in a way).
Question is, how do I make sure my test is executed each time the route is loaded?
In the egghead videos series (http://www.egghead.io/video/rbqRJQZBF3Q) he uses a function assigned to the controller but this doesn't seem like the right solution for a production app (I don't want to assign a function to a specific controller and I do believe the Angularjs dependency injection won't work).
A resolve is a property you can attach to a route in both ngRoute and the more robust UI router. A resolve contains one or more promises that must resolve successfully before the route will change.
We use $routeProvider to configure the routes. The config() takes a function that takes the $routeProvider as a parameter and the routing configuration goes inside the function. The $routeProvider is a simple API that accepts either when() or otherwise() method. We need to install the ngRoute module.
Answer: A is the correct answer. The $routeProvider is a service.
Creating a Default Route in AngularJS The below syntax just simply means to redirect to a different page if any of the existing routes don't match. otherwise ({ redirectTo: 'page' }); Let's use the same example above and add a default route to our $routeProvider service. function($routeProvider){ $routeProvider.
service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working
var app = angular.module('ajay.singhApp', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
resolve: {
myVar: function (repoService) {
return repoService.getItems().then(function (response) {
return response.data;
});
}
}
})
.when('/view2', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
app.factory('repoService', function ($http) {
return {
getItems: function () {
return $http.get('TextFile.txt');
}
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With