angular.module('pipelineChromeApp', [
'ngResource',
'ngSanitize',
'ngRoute',
'LocalStorageModule'
])
angular.module('pipelineChromeApp')
.factory('Profile', [
'$http',
'apiUrl',
'localStorageService',
function ($http, apiUrl, localStorageService) {
var baseUrl = apiUrl + 'profile.json?api_key=';
return {
login: function(apiKey) {
return $http.get(baseUrl + apiKey);
},
logout: function() {
localStorageService.clearAll();
localStorageService.set('loggedIn', false);
console.log("cleared local storage");
return true;
}
}
}]);
angular.module('pipelineChromeApp')
.controller('LoginController', [
'$scope',
'Profile',
'$location',
function ($scope, Profile, $location) {
$scope.apiKey = "";
$scope.login = function(){
debugger
// Profile.login().then({
// $location.path( "/actions" );
// });
};
}]);
For some reason Profile isn't available in LoginController. Have I loaded things wrong?
As you mentioned in your comment, the problem you have is in the console, and I assume the browser you're using is chrome. In chrome/v8, the javascript engine tries very hard to optimize your code, it will remove any unused function parameters. In your case, Profile isn't used anywhere in your function, so v8 has removed it.
That's also the reason why it works fine when you have some code to do with the Profile.
Usually I will add a console.log() to an empty function if I want to check some variables in the chrome console, like this:
$scope.login = function() {
debugger;
console.log(Profile);
};
Related
I'm a bit frustrated because I can't figure out whats up with the AngularJS $log service. I don't use it often but I have it working on another part of my site, the only reason I could think it wouldn't be working would be something to do with the block scope inside the then function. In my console I get the following error when trying to run $log.debug:
TypeError: $log.debug is not a function
at analysis.client.controller.js:23
at processQueue (angular.js:14551)
at angular.js:14567
at Scope.$get.Scope.$eval (angular.js:15830)
at Scope.$get.Scope.$digest (angular.js:15641)
at angular.js:15869
at completeOutstandingRequest (angular.js:5387)
at angular.js:5659
Heres my analysis.client.controller.js file:
'use strict';
angular.module('analysis').controller('AnalysisController', ['$scope', '$timeout', '$mdSidenav', '$mdComponentRegistry', '$log', 'Authentication',
function($scope, $timeout, $mdSidenav, $mdComponentRegistry, $log, Authentication) {
$scope.user = Authentication.user;
// Option #1
//
// $scope.isOpen = function() { return $mdSidenav('right').isOpen(); };
// $scope.toggle = function() { $mdSidenav('right').toggle() };
// Option #2 - See https://github.com/angular/material/issues/974
$scope.toggle = angular.noop;
$scope.isOpen = function() {
return false;
};
$scope.toggleLeft = function() {
$mdSidenav('left').toggle()
.then(function() {
$log.debug('toggle left is done');
});
};
}
]);
Thanks in advance for any help!
The debug method is not enabled by default because not all browsers support console.debug, but you can enable it in the configuration phase of your app with the $logProvider.
'use strict';
angular.module('analysis')
.config(function($logProvider){
$logProvider.debugEnabled(true);
})
.controller('AnalysisController', function(
$scope,
$timeout,
$mdSidenav,
$mdComponentRegistry,
$log,
Authentication
) {
$scope.user = Authentication.user;
// Option #1
//
// $scope.isOpen = function() { return $mdSidenav('right').isOpen(); };
// $scope.toggle = function() { $mdSidenav('right').toggle() };
// Option #2 - See https://github.com/angular/material/issues/974
$scope.toggle = angular.noop;
$scope.isOpen = function() {
return false;
};
$scope.toggleLeft = function() {
$mdSidenav('left').toggle().then(function() {
$log.debug('toggle left is done');
});
};
});
$log's debug method is disabled by default. You need to enable $log from app config phase like below.
app.config(function($logProvider){
$logProvider.debugEnabled(true);
});
FYI, I got this same error when I inadvertently reassigned the debug method instead of calling it.
$log.debug = 'My log message'
Instead of:
$log.debug('My log message')
After browsing to the page that had the bad statement, I would get "TypeError: $log.debug is not a function" on my other pages that had log statements.
This is my code to implement in my application a login procedure. The application has to verify the cookie set by the server and continue with the login procedure by redirect the user to canvas state. My issue is that I get the above mentioned error. Actually it works that is the login is made successfully but I would like to get rid of this error. I guess that the error should be in the $stateChangeStart but I don't know how to fix it. any idea?
(function() {
'use strict';
angular
.module('app', [
'ui.router',
'ngResource',
'ngCookies',
'app.login'
])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/login');
})
.run(function($rootScope, AuthService, RedirectService) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (!AuthService.isAuthenticated()) {
// the user isn't authenticated
event.preventDefault();
// redirect to the server side
RedirectService.redirectToAuth();
}
});
});
})();
(function() {
'use strict';
angular
.module('app.login')
.factory('AuthService', Auth);
Auth.$inject = ['Cookie', 'Session'];
function Auth(Cookie, Session) {
return {
login: function(params) {
// here set the session with params passed by the server
Session.create(params.id, params.data.id, params.data.make, params.data.name);
},
isAuthenticated: function() {
// check cookie here set in the server side
return Cookie.exist();
}
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.service('Cookie', Cookie);
Cookie.$inject = ['$cookies'];
function Cookie($cookies) {
this.authCookie = $cookies.__cookie;
this.exist = function() {
return (this.authCookie ? true : false);
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.factory('RedirectService', Redirect);
Redirect.$inject = ['$window'];
function Redirect($window) {
return {
redirectToAuth: function() {
// redirect the user to the server for auth
$window.location.href = "http://" + $window.location.host + "/auth/facebook";
}
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.controller('LoginController', Login);
// here inject what function Login needs
Login.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AuthService'];
function Login($rootScope, $scope, $state, $stateParams, AuthService) {
var params = {
id: $stateParams.userid,
data: {
id: $stateParams.modelid,
make: $stateParams.modelmake,
name: $stateParams.modelname
}
};
$scope.login = function(params) {
AuthService.login(params);
// activate the canvas state
$state.go('canvas');
};
// run the login function to set the Session user with data passed by the server
$scope.login(params);
}
})();
Maybe this can help a little more:
/*
We are using the below urlRouterProvider.otherwise() because of:
https://github.com/angular-ui/ui-router/issues/600
*/
$urlRouterProvider.otherwise(function($injector, $location) {
var $state = $injector.get('$state');
$state.go('login');
});
With this code you can still use the otherwise(), the disadvantage of using when() is that other unknown routes will not match. Above code solved all of our infinite loops.
Fixed the issue
$urlRouterProvider.otherwise('/login');
caused all this issue.
removed it and replaced with when() solved the issue
Lets say i list all users in a list, when i click a user i want to route to a new view and get the data for the selected person.
What is the preferred way? Should i move the data i already got when i listed the users or should i create a new server call?
My first thought is to pass the data, but the problem with this is that the data the gets lost if the user refreshes the page.
What is the best practice to solve this?
Small example:
(function() {
var app = angular.module('app');
var controllerId = 'app.controllers.views.userList';
app.controller(controllerId, [
'$scope', 'UserService',function ($scope, userService) {
var vm = this;
vm.users = [];
userService.getAllUsers().success(function (data) {
vm.users= data.users;
});
var gotoUser = function(user) {
// Pass the user to UserDetail view.
}
}
]);
})();
<div data-ng-repeat="user in vm.users" ng-click="vm.gotoUser(user)">
<span>{{customer.firstname}} {{customer.lastname}}</span>
</div>
i now list the user details in UserDetail view, this view is now vulnerable against a browser refresh.
Typically most people just create a new server call, but I'll assume you're worried about performance. In this case you could create a service that provides the data and caches it in local storage.
On controller load, the controller can fetch the data from the service given the route params and then load the content. This will achieve both the effect of working on page refresh, and not needing an extra network request
Here's a simple example from one of my apps, error handling left out for simplicity, so use with caution
angular.
module('alienstreamApp')
.service('api', ['$http', '$q','$window', function($http, $q, $window) {
//meta data request functions
this.trending = function() {
}
this.request = function(url,params) {
var differed = $q.defer();
var storage = $window.localStorage;
var value = JSON.parse(storage.getItem(url+params))
if(value) {
differed.resolve(value);
} else {
$http.get("http://api.alienstream.com/"+url+"/?"+params)
.success(function(result){
differed.resolve(result);
storage.setItem(url+params,JSON.stringify(result))
})
}
return differed.promise;
}
}]);
I would say that you should start off simple and do a new server call when you hit the new route. My experience is that this simplifies development and you can put your effort on optimizing performance (or user experience...) where you will need it the most.
Something like this:
angular.module('app', ['ngRoute', 'ngResource'])
.factory('Users', function ($resource) {
return $resource('/api/Users/:userid', { userid: '#id' }, {
query: { method: 'GET', params: { userid: '' }, isArray: true }
});
});
.controller("UsersController",
['$scope', 'Users',
function ($scope, Users) {
$scope.loading = true;
$scope.users = Users.query(function () {
$scope.loading = false;
});
}]);
.controller("UserController",
['$scope', '$routeParams', 'Users',
function ($scope, $routeParams, Users) {
$scope.loading = true;
$scope.user = Users.get({ userid: $routeParams.userid }, function () {
$scope.loading = false;
});
$scope.submit = function () {
$scope.user.$update(function () {
alert("Saved ok!");
});
}
}]);
.config(
['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/users', {
templateUrl: '/users.html',
controller: 'UsersController'
})
.when('/users/:userid', {
templateUrl: '/user.html',
controller: 'UserController'
})
.otherwise({ redirectTo: '/users' });
}
]
);
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.
This is probably a matter of me not handling dependency injection proper, but I'm trying to make a 'Session' service available to my SessionsController. Here's my SessionsController:
angular.module('App.controllers').controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.foo = function() {
console.log("clicked foo..");
}
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save()
.success(function(data, status, headers, config) {
$cookieStore.put('_app_user', data);
});
}
};
$scope.destroy = function() {
$scope.session.$destroy();
};
}]);
Here's the actual Session service definition:
angular.module('App.services').service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = $cookieStore.get('_app_user');
this.signedIn = !!$cookieStore.get('_app_user');
this.signedOut = !this.signedIn;
this.userSession = new UserSession( { email:"foo#bar.com", password:"example", remember_me:true } );
//this.userRegistration = new UserRegistration( { email:"foo-" + Math.floor((Math.random()*10000)+1) + "#bar.com", password:"example", password_confirmation:"example" } );
$rootScope.$on('$routeChangeStart', function (current, next) {
if (this.signedOut && next !== '/login') {
console.log("relocating user..");
//$location('/login');
}});
}]);
And here's how I strung it together:
angular.module('App.resources', ['ngResource']);
angular.module('App.services', ['ngResource']);
angular.module('App.directives', []);
angular.module('App.filters', []);
angular.module('App.controllers', ['ngCookies', 'Session']);
var App = angular.module("App", ['App.resources', 'App.services', 'App.directives', 'App.filters', 'App.controllers', 'ui.compat', '$strap.directives', 'templates']);
Clearly missing something to string everything together as Firebug is complaining that there is no module named: Session.
Firebug is right, you have no module named session. You have a service named Session in the App.services module.
Just remove the Session module injection, and you are good to go.
angular.module('App.controllers', ['ngCookies']);