I want to make sure, that my app checks on certain routs if it is still authenticated. To do that I added to my routes:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/profile',{
templateUrl: 'templates/user/profile.html',
controller: 'ProfileCtrl',
resolve: [ 'SessionCheck' ]
}).
.......
I have a factory which handles the ['SessionCheck']
AppFactories.factory("SessionCheck", ['$http','$q','FlashService',
function($http,$q,FlashService) {
var def = $q.defer();
var SessionStatus = $http.get('/sessioncheck', {cache: false});
if(SessionStatus.success){
def.resolve();
}else{
FlashService.show(SessionStatus.data.flash);
def.reject;
}
return def.promise;
}]);
I can see that the link is being called, but only once. Every time I click on a route with the resolve property the sessioncheck is not send to the server.... I already tried to put cache on false, but still. What am I doing wrong?
I suspect the problem is how you are using the resolver. Try something like this:
in the factory:
AppFactories.factory("SessionCheck", ['$http','$q','FlashService', function($http,$q,FlashService) {
return {
resolve: function () {
var def = $q.defer();
var SessionStatus = $http.get('/sessioncheck', {cache: false});
if(SessionStatus.success){
def.resolve();
}else{
FlashService.show(SessionStatus.data.flash);
def.reject;
}
return def.promise;
}
};
}]);
and in the router:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/profile',{
templateUrl: 'templates/user/profile.html',
controller: 'ProfileCtrl',
resolve: [ 'SessionCheck', function(sessionCheck) {
return sessionCheck.resolve();
}]
}).
.......
Related
I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}
Right now i am making an AngularJS+UI router install application. But i have a problem, the problem is, that i want to disable access to the views, associated with the install application. I want to do it in resolve in the state config.
But the problem is i need to get the data from a RESTful API, whether the application is installed or not. I tried making the function, but it loaded the state before the $http.get request was finished.
Here was my code for the resolve function:
(function() {
var app = angular.module('states', []);
app.run(['$rootScope', '$http', function($rootScope, $http) {
$rootScope.$on('$stateChangeStart', function() {
$http.get('/api/v1/getSetupStatus').success(function(res) {
$rootScope.setupdb = res.db_setup;
$rootScope.setupuser = res.user_setup;
});
});
}]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404");
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
data: function($q, $state, $timeout, $rootScope) {
var setupStatus = $rootScope.setupdb;
var deferred = $q.defer();
$timeout(function() {
if (setupStatus === true) {
$state.go('setup-done');
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
})
.state('user-registration', {
url: "/install/user-registration",
templateUrl: "admin/js/partials/user-registration.html",
controller: "RegisterController"
})
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html"
})
.state('404', {
url: "/404",
templateUrl: "admin/js/partials/404.html"
});
}]);
})();
EDIT:
Here is what my ajax call returns:
Try this way:
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
setupStatus: function($q, $state, $http) {
return $http.get('/api/v1/getSetupStatus').then(function(res) {
if (res.db_setup === true) {
$state.go('setup-done');
return $q.reject();
}
return res;
});
}
}
})
Then inject setupStatus in controller:
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html",
controller: ['$scope', 'setupStatus', function ($scope, setupStatus) {
$scope.setupdb = setupStatus.db_setup;
$scope.setupuser = setupStatus.user_setup;
}]
})
In a MEAN app, I have an authService module with an Auth factory which contains an authFactory.isLoggedIn function:
// check if a user is logged in
// checks if there is a local token
authFactory.isLoggedIn = function() {
if (AuthToken.getToken())
return true;
else
return false;
};
So I thought I could use this with the resolve property of $routeProvider like this:
var MyModule = angular.module('app.routes', ['ngRoute']);
MyModule.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'app/views/pages/home.html'
})
// login page
.when('/login', {
templateUrl : 'app/views/pages/login.html',
controller : 'mainController',
controllerAs: 'login'
})
// register page
.when('/register', {
templateUrl: 'app/views/pages/register.html',
controller: 'userCreateController',
controllerAs: 'register'
})
// upload page
.when('/upload', {
templateUrl : 'app/views/pages/upload.html',
controller: 'uploadController',
controllerAs: 'userupload',
resolve: function($q, $location) {
var deferred = $q.defer();
deferred.resolve();
if (!Auth.isLoggedIn) {
$location.path('/login');
}
return deferred.promise;
}
})
//logout
.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
}]);
Unfortunately this doesn't work to stop unauthenticated users accessing the upload page and I don't see any errors being reported.
I have seen instances of simpler ways to do this eg:
.when('/upload', {
templateUrl : 'app/views/pages/upload.html',
controller: 'uploadController',
controllerAs: 'userupload',
isLoggedIn: true
})
But that doesn't work either, which is a shame as it's far simpler.
In the end I was determined to use the resolve property of $routeProvider so after experimenting with the solution on http://midgetontoes.com/blog/2014/08/31/angularjs-check-user-login
I came up with:
var MyModule = angular.module('app.routes', ['ngRoute']);
MyModule.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
var onlyLoggedIn = function($location, $q, Auth) {
var deferred = $q.defer();
if (Auth.isLoggedIn()) {
deferred.resolve();
} else {
deferred.reject();
$location.url('/login');
}
return deferred.promise;
};
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'app/views/pages/home.html'
})
// login page
.when('/login', {
templateUrl : 'app/views/pages/login.html',
controller : 'mainController',
controllerAs: 'login'
})
// register page
.when('/register', {
templateUrl: 'app/views/pages/register.html',
controller: 'userCreateController',
controllerAs: 'register'
})
// upload page
.when('/upload', {
templateUrl : 'app/views/pages/upload.html',
controller: 'uploadController',
controllerAs: 'userupload',
resolve:{loggedIn:onlyLoggedIn}
})
//logout
.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
}]);
I am sure this isn't as good as the custom http interceptor as posited by #Dimitiri Algazin or as simple as the solution from #Pasan Ratnayake but it does fulfil my quest to use resolve. Thanks to #Dimitri and #Pasan anyway.
Add custom http interceptor. This is not exact code, just algorithm, some syntax might missing:
.factory('myHttpInterceptor', function($q, $location, AuthToken) {
function isLoggedIn() {
return !!AuthToken.getToken();
}
function canRecover(response) {
var status = response.status;
var config = response.config;
var method = config.method;
var url = config.url;
console.log("--->>> ", method, status, url);
if (status == 401) {
alert("401");
} else if ( status == 403) {
alert("403");
} else if (status == 404) {
alert("404");
} else if (status == 405) {
alert("405");
} else if (status == 500) {
alert("500");
} else {
}
return response;
}
return {
// optional method
'request': function(config) {
if (isLoggedIn()) {
return config;
} else {
$location.path('login');
}
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'requestError': function(rejection) {
return $q.reject(canRecover(rejection));
},
// optional method
'responseError': function(rejection) {
return $q.reject(canRecover(rejection));
}
};
})
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
}])
There are multiple ways you could achieve this functionality.
Easiest would be to add a check similar to below code to each controller that you don't want your users to access.
// You could re-direct the user to a '401' state as well
if (!authFactory.isLoggedIn())
$state.go('login');
I want to make my views show only after the initial data is fetched and i am trying to accomplish this with a route resolve, but i can't get it to work. What am i doing wrong? Also my angular skills are a bit shabby so i aplogize in advance if my question is dumb.
Application.js :
var Application = angular.module('ReporterApplication', ['ngRoute']);
Application.config(['$routeProvider', '$interpolateProvider',
function($routeProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
$routeProvider
.when('/packing/scan.html', {
templateUrl: 'packing/scan.html',
controller: 'PackingScanController',
resolve: {
initData : Application.PackingScanInit()
}
})
.when('/packing/stats.html', {
templateUrl: 'packing/stats.html',
controller: 'PackingStatisticsController'
})
etc
and here is my Scan.js file :
Application.PackingScanInit = function ($q,$timeout,$http) {
var serverData = "";
$http.get('/packing/scan.action')
.success(function(data){
serverData = data;
})
.error(function(data){
serverData = data;
});
return serverData;
}
Application.controller('PackingScanController', ['initData', '$scope', '$http', function(initData, $scope, $http) {
var packer = this;
// Message log model
packer.messageLog = [{
status : "",
message : null
}];
the files are included in this order.
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');
}
};
});
Try this:
Application.PackingScanInit = function ($q,$timeout,$http) {
return $http.get('/packing/scan.action')
.success(function(data){
return data;
})
.error(function(data){
return data;
});
}
Also you have to adjust your resolve to this:
resolve: {
initData : Application.PackingScanInit
}
Here is a specific working example:
(function() {
angular.module('app',['ngRoute']);
function TestCtrl($scope, initData) {
$scope.value = initData;
}
angular.module('app').config(function($routeProvider) {
$routeProvider.otherwise({
template: '`<p>Dude {{value}}</p>`',
controller: TestCtrl,
resolve: {
initData: function($http) {
return $http.get('test.json') //change to test-e.json to test error case
.then(function(resp) {
return resp.data.value; //success response
}, function() {
return 'Not Found'; // error response
});
}
}
});
});
})();
http://plnkr.co/edit/SPR3jLshcpafrALr4qZN?p=preview
var testApp = angular.module('testApp', ['firebase'])
.config(['$routeProvider','$locationProvider',function
($routeProvider,$locationProvider)
{
$routeProvider
.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
})
.when('/test', {
templateUrl: '/views/test.html',
controller: testCrtl,
resolve:
{
firedata: function($q,angularFire){
var deffered = $q.defer();
var ref = new Firebase('https://shadowfax.firebaseio.com/items');
ref.on('value', function(result){
deffered.resolve(result.val());
});
return deffered.promise;
}
}
})
.otherwise({
redirectTo: '/'
});
// $locationProvider.html5Mode( true );
}]);
angular.module('testApp')
.controller('MainCtrl', ['$scope','$routeParams','$rootScope', function ($scope,$routeParams,$rootScope) {
$scope.load = function(){ return false;}
$rootScope.$on('$routeChangeStart', function(next, current) {
$scope.load = function(){ return true;}
});
}]);
testApp.controller('TestCtrl',['$scope','$timeout','Fire','firedata','testCrtl']);
var testCrtl = function ($scope,$timeout,Fire,firedata) {
$scope.items=firedata;
};
In the code above, why is the value of $scope.items=firedata; null? Please explain how can I perform a Google-like route change to preload data for the controller? This example works like John Lindquist explains, but when I use Firebase's native JS library, I can't get the data preloaded.
Also, using the Firebase angularFire library doesn't help, because it uses $scope as a parameter and it's not possible to pass $scope to the resolve function.
You should be able to use angularFireCollection to preload data:
.when('/test', {
templateUrl: '/views/test.html',
controller: testCrtl,
resolve: {
firedata: function(angularFireCollection){
return angularFireCollection('https://shadowfax.firebaseio.com/items');
}
}
})