I'm trying to fetch data (units) for a route (app.units). Here's the code.
.state('app.units', {
url: '/units',
views: {
'menuContent' :{
templateUrl: "templates/units.html",
controller: 'UnitCtrl',
resolve:{
units: function($stateParams, ExamService, $rootScope, $http){
return $http.get(ApiEndpoint.url +'/units.json?auth_token='+$rootScope.globals.currentUser.userToken)
.success(function(response){
//console.log('hello');
return response.data;
})
}
}
}
}
})
As you can see this won't resolve, doesn't show any errors in the console and gives me a blank page in my ionic app, yet the endpoint works with Advanced Rest Client for chrome. I've been stuck on this for age could someone please figure this out.
Hey i just refactored your code. Try it
.state('app.units', {
url: '/units',
views: {
'menuContent' :{
templateUrl: "templates/units.html",
controller: 'UnitCtrl',
resolve:{
units : ['$stateParams','$q','ExamService','$rootScope', '$http',function ($stateParams,$q,ExamService,$rootScope, $http) {
var deferred = $q.defer();
$http.get(ApiEndpoint.url +'/units.json?auth_token='+$rootScope.globals.currentUser.userToken)
.success(function(response){
//console.log('hello');
if(response!=undefined)
deferred.resolve(response);
else
deffered.reject();
})
return deferred.promise;
}]
}
}
}
})
Related
I'm working on authentication with angularjs, so after connecting my user I want to redirect him to the home page:
$scope.submit = function(user) {
var request = {
method: 'POST',
url: 'http://localhost:9001/signIn',
headers: {
'Content-Type': 'application/json'
},
data: {
"email": user.email,
"password": user.password,
"rememberMe": true
}
};
$http(request).then(function(data) {
$location.path('/home');
}, function(error) {
console.log(error);
});
};
here is my configuration:
app.config(function($urlRouterProvider, $stateProvider, $httpProvider, $authProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
.state('signIn', {
url: '/signIn',
templateUrl: '/signIn',
controller: 'SignInCtrl'
});
});
I tried this:
$http(request).then(function(data) {
$scope.$evalAsync(function() {
$location.path('/home');
});
console.log(data);
}, function(error) {
console.log(error);
});
also :
$location.path('/home');
$location.replace();
Neither of the above work, any help is greatly appreciated.
The home state resolver function fails to resolve or reject the $q.defer promise when $auth.isAuthenticated() returns false. This will cause the promise to hang and create a memory leak.
//ERRONEOUS CODE
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
//FAILS to resolve or reject promise
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
Instead return a rejection when not authenticated:
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
//var deferred = $q.defer();
if ($auth.isAuthenticated()) {
return $q.resolve("AUTHENTICATED");
};
//otherwise
return $q.reject("NOT AUTHENTICATED");
})
}
})
When a resolver function returns a rejected promise, the state change will be prevented and the $stateChangeError event will be broadcast on $rootScope.
I am hitting this url
http://localhost:8001/#/verifyMail?4c4e77a2
at that time i did
console.log($stateParams);
It shows empty object
My route is
.state('mailVerification', {
url: "/verifyMail?id",
templateUrl: "app/views/common/emailVerification.html",
controller: 'accountCtrl',
data: {
authorizedRoles: [USER_ROLES.all]
}
})
Why i am not getting $stateParams.id value? Please help me.
You need to resolve the data.
.state('mailVerification', {
url: "/verifyMail?id",
templateUrl: "app/views/common/emailVerification.html",
resolve: {
id: function($stateParams){
return $stateParams.id;
}
}
controller: 'accountCtrl',
data: {
authorizedRoles: [USER_ROLES.all]
}
})
and inside the controller:
.controller('accountCtrl', ['id', '$log', function(id, $log){
$log.debug(id);
}]);
I am creating a mobile app in AngularJS. I call a resource that calls an API to give me values. Everything works fine, but with slow connections or 3G $ scope not cool me, and therefore when browsing the list of items is old.
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});
If you want to reload a part of your controller logic, every time the view is activated:
.controller('ExerciseController', function(
$q,
$scope,
$state,
Exercises,
$ionicView
) {
// reload exercises every time when we enter in the controller
$ionicView.enter(function(){
// This gets executed regardless of ionicCache
Exercises.query(function(data) {
$scope.exercises = data;
});;
});
});
Else, you can use the reload option on .state()
I am creating a mobile app in angularjs . I call a resource that calls an API to give me values. Everything works fine , but with slow connections or 3G $ scope not cool me and therefore when browsing the list of items is old
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});
The documentation for resolve doesn't specify if there are any gotcha regarding the choice of key name.
So if I have code like the following will the controllers get the same promise or the correct one?
...
$stateProvider.state('myState', {
controller: 'ControllerA',
resolve:{
promiseObj: function($http) {
return $http({method: 'GET', url: '/someUrl'});
}
}
}).state('otherState', {
controller: 'ControllerB',
resolve: {
promiseObj: function($http) {
return $http({method: 'GET', url: '/someOtherUrl'});
}
}
});
...
.controller('ControllerA', ['promiseObj', function(promiseObj) {...}])
.controller('ControllerB', ['promiseObj', function(promiseObj) {...}])
The resolves names can be re-used (with caution, of course). They can even be overridden in a child resolve. The child resolve can even depend on the parent resolve.
$stateProvider.state('myState', {
controller: 'ControllerA',
resolve:{
promiseObj: function($http) {
return $http({method: 'GET', url: '/someUrl'});
}
}
}).state('otherState', {
controller: 'myState.Child',
resolve: {
promiseObj: function($http, promiseObj) { // the parent resolve data is injected as promiseObj
return $http({method: 'GET', url: '/someOtherUrl'});
}
}
});