I'm reading a book called MEAN Machine, and as I'm getting to the late chapters, I've got stuck at one of the sample applications, that doesn't seem to work.
The problem seems to occur because my mainController calls authService's Auth.getUser()
method, which may return either a $http.get()
or a $q.reject()
. As I'm not logged in, it returns $q.reject()
, and fails to chain the .success()
promise.
It throws following exception:
TypeError: undefined is not a function at mainCtrl.js:13
My code is as follows.
CONTROLLERmainController
angular.module('mainCtrl', [])
.controller('mainController', function($rootScope, $location, Auth) {
var vm = this;
// check to see if a user is logged in on every request
$rootScope.$on('$routeChangeStart', function () {
vm.loggedIn = Auth.isLoggedIn();
// get user information on route change
Auth.getUser()
/* ========= PROBLEM HERE ========= */
.success(function (data) {
vm.user = data;
});
});
// ... other stuff
});
SERVICEauthService
angular.module('authService', [])
// ===================================================
// auth factory to login and get information
// inject $http for communicating with the API
// inject $q to return promise objects
// inject AuthToken to manage tokens
// ===================================================
.factory('Auth', function ($http, $q, AuthToken) {
var authFactory = {};
// get the user info
/* ========= PROBLEM LEADS HERE ========= */
authFactory.getUser = function () {
if (AuthToken.getToken())
return $http.get('/api/me', { cache: true });
else {
return $q.reject({ message: 'User has no token.' });
}
}
What am I missing?
.isLoggedIn()
method inAuth
? – Lyndialyndon