Goal:
In my application every controller should be initialized after a user has a session / is logged in, because in this controller I use the data of logged in user.
Code:
app.js
app.run(function($q, $rootScope, AuthSvc){
$rootScope.ajaxCall = $q.defer();
AuthSvc.reloadSession().then(
function(response){
if(response!=null && response!=undefined){
$rootScope.activeUserSession = response;
$rootScope.ajaxCall.resolve();
}else{
$rootScope.activeUserSession = null;
$rootScope.ajaxCall.reject();
}
});
return $rootScope.ajaxCall.promise;
});
routes.js
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/timeTracking', {
templateUrl: 'partials/timeTracking/projectView.html',
controller: 'timeTrackingController',
resolve: {
response: function($rootScope, $q) {
var defer = $q.defer();
$rootScope.ajaxCall.promise.then(
function(){
defer.resolve();
return defer.promise;
});
}
}
}).
Problem: Controller gets initialized sometimes before the user has a session, I do not understand why.
Sorry I am new to Angular and my english is also crap, so I hope nevertheless you can understand what is my problem.
I think placing your session reload into the app.run is not the right place. Add it directly to resolve and checkout the docs for $q to learn how promises are working.
Because you can't call a promise or defer. You need to call a function that's returning a promise then you can add your then method to do your stuff after the promise is resolved.
Please have a look at the demo below or here at jsfiddle.
It's just an asynchronous method with $timeout to simulate the auth because I don't have a backend to add in the demo.
You can add your AuthSvc directly into resolve.
angular.module('demoApp', ['ngRoute'])
.controller('timeTrackingController', function($scope, response) {
$scope.data = response;
})
.factory('authService', function($q, $timeout) {
return {
reloadSession: function() {
var deferred = $q.defer();
$timeout(function() {
// just simulate session reload
// real api would to the job here
console.log('resolved defer now!!');
deferred.resolve({dummyData: 'hello from service'});
}, 1000);
return deferred.promise;
}
}
})
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/timeTracking', {
templateUrl: 'partials/timeTracking/projectView.html',
controller: 'timeTrackingController',
resolve: {
response: function(authService) {
return authService.reloadSession().then(function(data) {
return data;
})
}
}
})
.otherwise('/timeTracking');
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-route.js"></script>
<div ng-app="demoApp">
<script type="text/ng-template" id="partials/timeTracking/projectView.html">
project view: {{data | json}}
</script>
<div ng-view=""></div>
</div>
Related
Right now i am trying to make an Angular JS install application, to install a CMS. So i am trying to block access to a state (ui router), i am doing it with a resolve function. But the problem is, that i make a get request to an API, which returns true or false, and the resolve function do not wait for the get request to complete, so it just loads the state.
Here is my code:
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"
});
}]);
Here you can see a timeline for the loading of the page:
Here you can see what the API returns:
Your db-install resolver function needs to chain from the $http.get for install status.
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
data: function($state, $http) {
return $http.get('/api/v1/getSetupStatus'
).then (function(result) {
var setupdb = result.data.db_setup;
var user_setup = result.data.user_setup;
//return for chaining
return setupdb;
}).then (function (setupStatus) {
//use chained value
if (setupStatus === true {
//chain with $state.go promise
return $state.go('setup-done');
} else {
//resolve promise chain
return 'setup-not-done';
};
})
}
}
})
By returning and chaining from the status $http.get, the resolver function waits before executing (or not executing) the $state.go.
For more information on chaining promises, see the AngularJS $q Service API Reference -- chaining promises.
The call to getSetupStatus gets executed in the $stateChangeStart so resolve is not aware that it has to wait. You can put the $http call inside of the resolve function, like this:
function($q, $state, $timeout) {
return $http.get('/api/v1/getSetupStatus')
.then(function(res) {
if(res.db_setup) {
$state.go('setup-done');
}
else {
return true;
}
});
}
By making the resolve parameter return a callback the state will load after the promise is resolved.
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'm working on a mobile app using AngularJS as a framework, currently I have a structure similar to this:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'homeCtrl'
})
.when('/one', {
templateUrl : 'pages/one.html',
controller : 'oneCtrl'
})
.when('/two', {
templateUrl : 'pages/two.html',
controller : 'twoCtrl'
});
}]);
app.controller('homeCtrl', ['$scope', function($scope) {
}]);
app.controller('oneCtrl', ['$scope', function($scope) {
}]);
app.controller('twoCtrl', ['$scope', function($scope) {
}]);
And then I'm displaying the content with an ng-view:
<div class="ng-view></div>
Things are working well but I need to load data from a JSON file to populate all the content of the app. What I want is to make and an AJAX call only once and then pass the data through all my different controllers. In my first attempt, I thought to create a Service with an $http.get() inside of it and include that in every controller, but it does not work because it makes a different ajax request everytime I inject and use the service. Since I'm new using angular I'm wondering what is the best way or the more "angular way" to achieve this without messing it up.
Edit: I'm adding the code of the service, which is just a simple $http.get request:
app.service('Data', ['$http', function($http) {
this.get = function() {
$http.get('data.json')
.success(function(result) {
return result;
})
}
});
Initialize the promise once, and return a reference to it:
No need to initialize another promise. $http returns one.
Just tack a .then() call on your promise to modify the result
angular.module('app', [])
.service('service', function($http){
this.promise = null;
function makeRequest() {
return $http.get('http://jsonplaceholder.typicode.com/posts/1')
.then(function(resp){
return resp.data;
});
}
this.getPromise = function(update){
if (update || !this.promise) {
this.promise = makeRequest();
}
return this.promise;
}
})
Codepen example
Edit: you may consider using $http cache instead. It can achieve the same results. From the docs:
If multiple identical requests are made using the same cache, which is not yet populated, one request will be made to the server and remaining requests will return the same response.
Try this to get JSON Data from a GET Link:
(function (app) {
'use strict';
app.factory('myService', MyService);
MyService.$inject = ['$q', '$http'];
function MyService($q, $http) {
var data;
var service = {
getData: getData
};
return service;
//////////////////////////////////////
function getData(refresh) {
if (refresh || !data) {
return $http.get('your_source').then(function(data){
this.data = data;
return data;
})
}
else {
var deferrer = $q.defer();
deferrer.resolve(data);
return deferrer.promise;
}
}
}
}(angular.module('app')));
Now you can add this dependency in your controller file and use:
myService.getData().then(function(data){
//use data here
}, function(err){
//Handle error here
});
I'm new to angular and I have a user route which I'm attempted to resolve the user object for before rendering the view. I've injected $q and deferred the promise, however, the view is still loading before the promise is returned.
Route:
.when('/user/:userId', {
templateUrl: 'user/show.html',
controller: 'UserController',
resolve: {
user: userCtrl.loadUser
}
})
Controller
var userCtrl = app.controller('UserController', ['$scope',
function($scope){
$scope.user = user; // User is undefined
// This fires before the user is resolved
console.log("Fire from the controller");
}]);
userCtrl.loadUser = ['Restangular', '$route', '$q',
function(Restangular, $route, $q) {
var defer = $q.defer();
Restangular.one('users', $route.current.params.userId).get().then(function(data) {
console.log("Fire from the promise");
defer.resolve(data);
});
return defer.promise;
}];
After looking through the Github issues, I found a similar problem and resolved it with the following:
userCtrl.loadUser = ['Restangular', '$route',
function(Restangular, $route) {
return Restangular.one('users', $route.current.params.userId).get();
}];
I would like to delay the initialization of a controller until the necessary data has arrived from the server.
I found this solution for Angular 1.0.1: Delaying AngularJS route change until model loaded to prevent flicker, but couldn't get it working with Angular 1.1.0
Template
<script type="text/ng-template" id="/editor-tpl.html">
Editor Template {{datasets}}
</script>
<div ng-view>
</div>
JavaScript
function MyCtrl($scope) {
$scope.datasets = "initial value";
}
MyCtrl.resolve = {
datasets : function($q, $http, $location) {
var deferred = $q.defer();
//use setTimeout instead of $http.get to simulate waiting for reply from server
setTimeout(function(){
console.log("whatever");
deferred.resolve("updated value");
}, 2000);
return deferred.promise;
}
};
var myApp = angular.module('myApp', [], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/editor-tpl.html',
controller: MyCtrl,
resolve: MyCtrl.resolve
});
});
http://jsfiddle.net/dTJ9N/1/
Since $http returns a promise, it's a performance hit to create your own deferred just to return the promise when the http data arrives. You should be able to do:
MyCtrl.resolve = {
datasets: function ($http) {
return $http({method: 'GET', url: '/someUrl'});
}
};
If you need to do some processing of the result, use .then, and your promise is chained in for free:
MyCtrl.resolve = {
datasets: function ($http) {
return $http({method: 'GET', url: '/someUrl'})
.then (function (data) {
return frob (data);
});
}
};
You could always just put "ng-show" on the outer-most DOM element and set it equal to the data you want to wait for.
For the example listed on the Angular JS home page you can see how easy it is: http://plnkr.co/CQu8QB94Ra687IK6KgHn
All that had to be done was
That way the form won't show until that value has been set.
Much more intuitive and less work this way.
You can take a look at a near identical question here that uses resources, but it works the same way with $http. I think this should work
function MyCtrl($scope, datasets) {
$scope.datasets = datasets;
}
MyCtrl.resolve = {
datasets: function($http, $q) {
var deferred = $q.defer();
$http({method: 'GET', url: '/someUrl'})
.success(function(data) {
deferred.resolve(data)
}
return deferred.promise;
}
};
var myApp = angular.module('myApp', [], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/editor-tpl.html',
controller: MyCtrl,
resolve: MyCtrl.resolve
});
});