How to avoid asynchronous processing in angular js - angularjs

I'm new in angular js . I want to do authentication . I've to direct to some pages only after checking authentication. I've checkLogin function for that. While calling that checkLogin function it take some processing time. If true it redirects corresponding page. If false it remains the same page. But while calling the checkLogin function the same time it process the app.config function concurrently. I need to to block it. I've to process that only after chcklogin.
var app = angular.module('myApp', ['ngRoute', 'ngResource','ngCsv', 'ui', 'ngSanitize', 'ngQuickDate', 'ui.tree', 'blueimp.fileupload','mentio']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/views/login.html',
controller: 'LoginController',
title: 'Login'
}).when('/signup', {
templateUrl: 'app/views/signup.html',
controller: 'SignUpController',
title: 'Sign Up'
}).when('/dashboard', {
templateUrl: 'app/views/dashboard.html',
controller: 'DashboardController',
title: 'Dashboard'});});
app.run(function($rootScope, $location, DataService) {
var unAuthenticatedPages = ["/", "/signup"];
var checkLogin = function() {
if (!$rootScope.isLoggedIn && unAuthenticatedPages.indexOf($location.path()) === -1) {
$location.path('/');
}
};
$rootScope.isLoggedIn = true;
DataService.getUserListById(1, function(user) {
$rootScope.user = user;
});
$rootScope.$on('$locationChangeStart', checkLogin);});

angularjs comes with a built in promise library $q which can be injected and used something like this:
var doSomething = function() {
var deferred = $q.defer();
//do someething here, when you're ready resolve the deferred object
deferred.resolve();
//this won't execute until deferred is resolved or rejected
return deferred.promise;
};
You can also return variables with your promise if required. You can then
doSomething().then(function() {
//this executes if the promise is resolved
}, function() {
//this executes if the promise is rejected
});

Related

Angular route not entering the resolve function

I'm adding route authentication to my angular app.
For some reason when I try to navigate to the logentries view, I cannot get the code in the resolve function to execute.
I've added a breakpoint using Chrome developer tools, but it doesn't get hit.
The view does get loaded, however.
I thought the resolve would get hit before the controller is instantiated and the view rendered.
Why isn't it?
(function () {
'use strict';
angular.module('app')
.config(appConfig)
.run(routeAuthentication);
routeAuthentication.$inject = ['$rootScope', '$location'];
function routeAuthentication($rootScope, $location) {
$rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
if (rejection === 'Not Authenticated') {
console.log('Not Authenticated for Route');
$location.path('/');
}
});
}
appConfig.$inject = ['$routeProvider'];
function appConfig($routeProvider) {
$routeProvider
.when("/logentries", {
templateUrl: "app/views/logEntries.html",
controller: "logEntries",
resolve: function ($q, $location) {
// Code not entering here as far as I can tell.
var deferred = $q.defer();
deferred.resolve();
if (true) { // TODO - use authenticationServce
$location.path('/login');
}
return deferred.promise;
}
})
// other routes
};
})();

inject service[declared in separate file] in app.config or use it in a controller

I am trying to use the code from here to show routes only when a promise is TRUE
I am following this for my directory structure
app
- Orders
-orders.html
-OrderController.js
-OrderService.js
Main-Config [app.js]
var myApp = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap','myApp.OrderController']);
myApp.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/orders', {
templateUrl: 'orders/orders.html',
controller: 'OrderController',
resolve:{
customerExpenses: function(OrderService){
return OrderService.getOrders($route.current.params.customerName);
}
}
})
})
OrderService.js
angular.module('myApp').factory('OrderService', ['$http', function($http) {
var sdo = {
getNames: function() {
var promise = $http({
method: 'GET',
url: ''
});
promise.success(function(data, status, headers, conf) {
return data;
});
return promise;
}
}
return sdo;
}]);
I have tried the Accepted answer from here, and one of the suggestion from another SO article
angular.module('myApp')
.service('FooService', function(){
//...etc
})
.config(function(FooServiceProvider){
//...etc
});
As I have my service in a different file, I am trying to determine if I can use it in app.js file without using provider or is that the only way to use service in app.config?
UPDATE 1:
If i want to use the service in a controller
angular.module('myApp.OrderController',[]).controller('OrderController', function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
});
I get OrderService not available
Have tried this:
angular.module('myApp.OrderController',[]).controller('OrderController', ['$scope','OrderService',function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
}]);
followed example :
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
but can not use my service. my controller and service are in different files
I added this question here as I feel they are somewaht related.
You have not injected your service OrderService, change your code in very first line
var myApp = angular.module('myApp', ['ngRoute','ngAnimate', ....'OrderService'])
myApp.config(function($routeProvider, $locationProvider, OrderService){
....
})
Rest of the code looks good

Loading controller on demand using AngularJS and RequireJS

I'm using Angular UI-router and trying to download/load controller when the routing changes. I used resolve and category, the data.data returns the js file content as string. I'm not sure to make the controller available to angular. Please help
My module.js contains below routing code
state("privacy", {
url: "/privacy",
controllerProvider: function ($stateParams) {
return "PrivacyController";
},
resolve: {
category: ['$http', '$stateParams', function ($http, $stateParams) {
return $http.get("js/privacy.js").then(function (data) {
return data.data;
});
} ]
},
templateUrl: localPath + "templates/privacy.html"
})
The below controller exist in "js/privacy.js"
socialinviter.controller("PrivacyController", function ($scope) {
$scope.me = "Hellow world";
});
I also tried with require js but I'm getting error "http://errors.angularjs.org/1.2.16/ng/areq?p0=PrivacyController&p1=not%20aNaNunction%2C%20got%20undefined"
resolve: {
deps: function ($q, $rootScope) {
var deferred = $q.defer(),
dependencies = ["js/privacy"];
require(dependencies, function () {
$rootScope.$apply(function () {
deferred.resolve();
});
deferred.resolve()
})
return deferred.promise;
}
}
I have resolved the issue and I thought the solution would be helpful for others
Step 1: On your config, include the parameter $controllerProvider
mytestapp.config(function ($stateProvider, $controllerProvider)
Step 2: telling angular to register the downloaded controller as controller, add the below inside the config
mytestapp.config(function ($stateProvider, $controllerProvider) {
mytestapp._controller = mytestapp.controller
mytestapp.controller = function (name, constructor){
$controllerProvider.register(name, constructor);
return (this);
}
......
Step 3: Add the resolve method as below
state("privacy", {
url: "/privacy",
controller: "PrivacyController",
resolve: {
deps : function ($q, $rootScope) {
var deferred = $q.defer();
require(["js/privacy"], function (tt) {
$rootScope.$apply(function () {
deferred.resolve();
});
deferred.resolve()
});
return deferred.promise;
}
},
templateUrl: "templates/privacy.html"
})

AngularJS working with $location.path and ngRoute

I have this $location.path redirection:
myapp.controller('registerCtrl', function ($scope, $location, regService) {
$scope.register = function() {
$('#regbutton').prop('disabled','disabled');
regService.createUser($scope.email, $scope.password, function(id) {
if (id) {
$('#register').modal('hide');
$location.path('/account');
}
});
}
})
When the redirection occurs it redirects the user to http://myapp.com/#/account
Now I want to display a different template to show the user account. So I'm trying to use ngRoute but cannot get it to work properly..
myapp.config(['$routeProvider', '$locationProvider', '$provide',
function ($routeProvider, $locationProvider, $provide) {
console.log('in');
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
$routeProvider.
when('/account', {
templateUrl: 'account.html',
resolve: {
// I will cause a 1 second delay
delay: function ($q, $timeout) {
console.log('in resolve');
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$locationProvider
.html5Mode(true)
.hashPrefix('');
}]);
The route you should be using in the configuration when() function is /account

promise is not resolved at controller injection

I'm facing an issue. I'm working with angular 1.2RC3 and ui-route 0.2.
If i resolve with a function which is doing a synchronous return, it works.
With a promise, the controller is initialized before resolving the promise.
http://plnkr.co/edit/feXHNaGsXwpXDBXkxLZx
angular.module('srcApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
var userResult = {
id : 'userid',
displayName : 'displayName'
};
var getUserPromise = function ($q, $timeout, $log) {
var defer = $q.defer;
$timeout(function () {
$log.log('promise resolved');
defer.resolve(userResult);
}, 2000);
return defer.promise;
};
$stateProvider.state('test', {
url: '/',
template: '<div>{{user.displayName}}</div>',
controller: 'testCtrl',
resolve : {
user: getUserPromise
}
});
});
var testCtrl = angular.module('srcApp').controller('testCtrl', function ($scope, $http, $log, user) {
$log.log("test controller init");
$log.log("test controller user=" + user);
$scope.user = user;
});
Weird... It's pretty much what I do line for line in an app.
Solved: http://plnkr.co/edit/oC5wK8aDcq82mWl8ES6l?p=preview
You typed:
$q.defer
instead of:
$q.defer()

Resources