How can I delay/defer a route/controller until an anonymous function returns? On app bootstrap, I default rootScope.me as guest account until it can check cookies for a logged in user.
I have a controller, testCtrl, that relies on rootScope.me data to load appropriate user data. The controller is fired before rootScope.me has a chance to be set to the user.
I know Angular has $q service for resolving promises, but am not sure how to apply this to routing.
angular
.module('DDE', [])
.run(['$rootScope', 'Me', function($rootScope, Me) {
$rootScope.me = {
username : 'Guest',
id : -1
};
if (Cookies.get('user_id') && Cookies.get('username')) {
Me.getProfile({user_id : Cookies.get('user_id')}).success(function (res) {
$rootScope.me = res;
}).error(function (err) {
console.log('Error: ', err);
});
}
}])
.config(['$routeProvider', '$httpProvider', '$authProvider',
$routeProvider.
when('/test', {
templateUrl: '/html/pages/test.html',
controller: 'testCtrl'
}).
.config(['$routeProvider', '$httpProvider', '$authProvider', '$stateProvider', '$urlRouterProvider',
function($routeProvider, $httpProvider, $authProvider, $stateProvider, $urlRouterProvider) {
//Cannot inject services like Me or $rootScope as I need
function loadProfile () {
Me.getProfile({user_id : Cookies.get('user_id')}).success(function (res) {
$rootScope.me = res;
}).error(function (err) {
console.log('Error: ', err);
});
}
$stateProvider.
state('test', {
url : '/test',
templateUrl: '/html/pages/test.html',
controller : 'testCtrl',
resolve : {
ProfileLoaded : function () {
return loadProfile();
}
}
});
edit: adding angular's ngRoute example.
You can look into ui-router's resolve. It basically waits for your promise to be resolved before loading/navigating to your state/route.
documentation
Each of the objects in resolve below must be resolved (via
deferred.resolve() if they are a promise) before the controller is
instantiated. Notice how each resolve object is injected as a
parameter into the controller.
Here's angular's ngRoute example from angular's documentation:
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
})
Related
I'm using the latest Angular + Firebase and trying to set up a login authorization system. I have home.html which contains login+signup links, going to login.html and adding credentials works just fine (logging correct UID when submittet) but it's supposed to route to dash.html but goes back to home.html.
I've figured out that it seem to be issues with my resolve functions because the problem disappears when I remove .otherwise. But I still want (need?) it there I think.
If I'm logged in (but redirected to home.html) I can still access dash.html through the URL and I cannot access it again if I use the logout function at dash.html and that's how it should be.
But I can't figure out why I'm redirected to home.html in the first place.
Here's some of the code, any help appreciated:
My .run, .config and routes.
app.run(['$rootScope', '$location',
function($rootScope, $location){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
$location.path('/home');
}
});
}]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider,
$locationProvider){
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);
My login controller:
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth',
'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
}).catch(function(error) {
console.log('There was an error: ', error);
});
};
}]);
And my factory and module:
var app = angular.module('app', ['firebase', 'ngRoute']);
app.factory('Auth', ['$firebaseAuth',
function($firebaseAuth){
var ref = new Firebase('https://url.firebaseio.com');
return $firebaseAuth(ref);
}]);
it has with your resolve issue.
If you look at the documentation firebase doc
you will see that they use the
$waitForSignIn
or
$requireSignIn
functions. I know that because I have done the same thing. Try that instead and it should work
How can I reload the Angular resolve with the reload?
My code :
.when('/dashbord', {
title: 'dashbord',
templateUrl: 'views/dashbord.php',
controller: 'dashbordController',
resolve: {
getDashbord: function (getDashbordService) {
return getDashbordService;
}
}
})
Reload function :
app.run(['$rootScope', '$route', '$templateCache', function ($rootScope, $route, $templateCache) {
$rootScope.changeRoute = function(){
var currentPageTemplate = $route.current.templateUrl;
$templateCache.remove(currentPageTemplate);
$route.reload();
};
}]);
The above function reload only the view. It doesn't reload the resolve.
How can i do it in angular ?
I created plunker for you that shows that
$route.reload()
fires resolve on state
I know this is a late answer, but one thing to keep in mind is that Angular services are singletons -- which means if you define your resolve function as a service (esp. one that makes an $http request), you will get the same results each time the route resolves.
For example, this uses an Angular service that makes an $http request, and won't make a new $http request on $route.reload():
angular.module('myApp').factory('getDashboardService', ['$http', function getDashboardService($http) {
return $http.get('/path/to/resource'); // returns a promise
}]).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/dashboard', {
title: 'dashboard',
templateUrl: 'views/dashboard.php',
controller: 'DashboardController',
resolve: {
getDashbord: 'getDashboardService' // refers to an Angular service
}
});
}]);
...but this will, because it is not an injected service:
angular.module('myApp').config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/dashboard', {
title: 'dashboard',
templateUrl: 'views/dashboard.php',
controller: 'DashboardController',
resolve: {
getDashboard: ['$http', function($http) {
return $http.get('/path/to/resource');
}]
}
});
});
Here is a JSFiddle: https://jsfiddle.net/sscovil/77ys9hz5/
I am currently working on an Angular app, but I am having difficulty implementing a promise with resolve. What I want to accomplish is in the following:
Get a users geolocation
Use the users geolocation as parameters for an API call to SongKick
After the data has been received from the API call successfully I want the home.html page to load with the data found in q.resolve
All want all of this to happen in order. Essentially, there is data I need to obtain before displaying my home page. The problem is that when I console log getLocation in my homeCtrl it is undefined. Anyone know why or have a better way to approach this kind of thing?
FYI:assignValues is a success callback after geolocation values have been defined.
routes.js
angular.module('APP', ['ui.router',
'APP.home',
'uiGmapgoogle-maps'
])
.config(function($urlRouterProvider, $stateProvider, uiGmapGoogleMapApiProvider) {
$stateProvider.state("home", {
url:"/",
templateUrl: '/home.html',
controller: 'homeCtrl',
resolve: {
getLocation: function(dataFactory, $q){
var q = $q.defer();
navigator.geolocation.getCurrentPosition(assignValues);
function assignValues(position) {
dataFactory.getMetroArea(position.coords.latitude, position.coords.longitude).then(function(data){
q.resolve(data);
return q.promise;
})
}
}
}
})
HomeCtrl.js
angular.module('APP.home',['APP.factory'])
.controller('homeCtrl', ['$rootScope', '$scope', '$http', '$location', 'dataFactory', 'artists','uiGmapGoogleMapApi', 'getLocation', homeCtrl])
function homeCtrl($rootScope, $scope, $http, $location, dataFactory, artists, uiGmapGoogleMapApi, getLocation){
$scope.googleMapsData = getLocation
}
dataFactory.js(left out rest of factory)
dataFactory.getMetroArea = function(lat, lon){
return $http.get('http://api.songkick.com/api/3.0/search/locations.json?location=geo:'+ lat + ',' + lon + '&apikey=APIKEY')
}
Resolve methods need to either return a promise, or actual data. Here's a cleaned up resolve method which include rejections (you don't want to leave your request hanging).
angular.module('APP', ['ui.router', 'APP.home', 'uiGmapgoogle-maps'])
.config(function($urlRouterProvider, $stateProvider, uiGmapGoogleMapApiProvider) {
$stateProvider.state("home", {
url: "/",
templateUrl: '/home.html',
controller: 'homeCtrl',
resolve: {
getLocation: function(dataFactory,$q) {
var q = $q.defer();
navigator.geolocation.getCurrentPosition(function(position){
dataFactory.getMetroArea(position.coords.latitude, position.coords.longitude).then(function(data){
q.resolve(data);
},function(err){
q.reject(err);
})
},function(err){
q.reject(err);
});
return q.promise;
}
}
});
});
I think your getLocation function should be
getLocation: function(dataFactory, $q){
var q = $q.defer();
navigator.geolocation.getCurrentPosition(assignValues);
function assignValues(position) {
dataFactory.getMetroArea(position.coords.latitude, position.coords.longitude)
.then(function(data){
q.resolve(data);
});
}
return q.promise;
}
I am using route resolver in angularjs,for user will be redirect to login if user is not logged in as follows,
$routeProvider
.when('/', {
templateUrl: 'app/components/main/dashboard.html',
controller: 'dashboardController',
resolve: {
login: function ($rootScope, $location) {
if (!$rootScope.currentUser) {
$location.path('/login');
}
}
}
})
Here I want use this login function in many other routes,So i can copy paste same resolve function to every where as follows,
.when('/items', {
templateUrl: 'app/components/item/list.html',
controller: 'itemController',
resolve: {
login: function ($rootScope, $location) {
if (!$rootScope.currentUser) {
$location.path('/login');
}
}
}
})
It is working fine,my question is,is there any way to avoid this duplication of codes or is there any other better method ?
I set up a github repository yesterday which is a starting point for a web app and contains this feature here
If you look in public/app/app-routes.js you will see I have added resolve functions as variables, then you can simply do this rather than writing a whole function each time:
Function
var checkLoggedIn = function($q, $timeout, $http, $window, $location, $rootScope) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') {
$rootScope.loggedInUser = user;
$window.sessionStorage['loggedInUser'] = JSON.stringify(user);
deferred.resolve();
}
// Not Authenticated
else {
$window.sessionStorage['loggedInUser'] = null;
$rootScope.loggedInUser = null;
deferred.reject();
$location.url('/login');
}
});
return deferred.promise;
};
checkLoggedIn.$inject = ["$q", "$timeout", "$http", "$window", "$location", "$rootScope"];
Route
.when('/profile', {
title: 'Profile',
templateUrl: '/app/templates/profile.html',
controller: 'ProfileController',
resolve: {
loggedIn: checkLoggedIn
}
})
Should be easily adaptable for your app. Hope that helps!
I am aware that the error which is in the title of this question is basically because in my controller I am injecting a Session service in my controller that has not been defined. I am currently looking at: Angular Devise for which I am rolling out in an application that is using rails but have angular and rails separate. My setup on the angular side is as followed:
main.js
angular.module('App.controllers', []);
angular.module('App.config', []);
angular.module('App.directives', [])
angular.module('App.resources', ['ngResource']);
angular.module('App.services', []);
var App = angular.module("App", [
"ngResource",
"ngCookies",
"$strap.directives",
"App.services",
"App.directives",
"App.resources",
"App.controllers",
"TotemApp.config"
], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "/login";
return;
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
});
Session.js
App.service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = function() {
return $cookieStore.get('_angular_devise_user');
}
this.signedIn = function() {
return !!this.currentUser();
}
this.signedOut = function() {
return !this.signedIn();
}
this.userSession = new UserSession( { email:"sample#email.com", password:"password", remember_me:true } );
this.userRegistration = new UserRegistration( { email:"sample#email.com", password:"password", password_confirmation:"password" } );
}]);
sessions_controller
App.controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save().success(function(data, status, headers, config) {
$cookieStore.put('_angular_devise_user', Session.userSession.email);
$location.path('/todos');
});
}
};
$scope.destroy = function() {
$cookieStore.remove('_angular_devise_user');
$scope.session.$destroy();
};
}]);
routes.js
'use strict';
App.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/sessions/new.html',
controller: 'SessionsController'
})
.when('/sign_up', {
templateUrl: 'views/registrations/new.html',
controller: 'RegistrationsController'
})
.otherwise({
redirectTo: '/'
});
});
This error occurs when I try to access the login page or register page. If someone can shed some light that would be greatly appreciated. Not entirely sure how to resolve this Error: Unknown provider: $SessionProvider <- $Session error
At first glance this looks correct. I can only assume that perhaps you've not included Session.js in your index.html file?
Angular clearly doesn't know what 'Session' service is so there's something wrong there either file not loaded, not loaded correctly or something along those lines as far as I can see.
Edit: Does the error say 'SessionProvider <- Session' or '$SessionProvider -< $session' because if it's the latter, then something is named wrong somewhere in your app since your service is named 'Session' not '$Session'.
When you have syntax error in other javascript or typescript files. You will get the same error. Please make sure that you have no syntax error.