I'm unable to get my Angular Service to connect - javascript

I'm trying to hook up a simple service that queries a php file. The user inputs a username and password, and clicks a button that runs this function (passing in $scope.password):
$scope.loginFunction = function(){
loginService.getLogin().then(function(response){
$rootScope.loggedIn = true;
}, function(error){
$rootScope.loggedIn = false;
});
};
The service looks like this:
.service('loginService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope){
var getLogin = function(scope) {
$http.post('login.php'), {
password: $scope.password
}, function (success) {
console.log("Login result: " + success);
}, function (error) {
console.log("Couldn't complete the login request.");
}
return({
getLogin: getLogin
})
}
}])
The error I get is: "TypeError: loginService.getLogin is not a function"
But at the top of my controller with the function, I have:
myApp.controller('myController', ['$scope', '$rootScope', '$filter', 'loginService', function myController($scope, $rootScope, $filter, loginService) {
Does anyone know why I'm getting this error?
Thanks!
Sorry, here is login.php:
<? echo $_POST['password'] == 'test123' ? true : false ?>

Try something more like..
myApp.service('loginService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope){
var service = {
getLogin: function(scope) {
$http.post('login.php'), {
password: $scope.password
}, function (success) {
console.log("Login result: " + success);
}, function (error) {
console.log("Couldn't complete the login request.");
}
}
};
return service;
}

var getLogin how you have it is a private function. This will work for you.
var app = angular.module("myApp", []);
app.service("loginService", ["$http","$q", function($http, $q) {
var loginService = this;
loginService.getLogin = function(password) {
//use this if you'd like to return promise
var defer = $q.defer();
//put password into a json object
var payload = {
password: password;
};
//upload payload to server, content-type must be json
$http.post("url/to/controller", payload, {
headers: { "Content-Type": "application/json" }
}).then(function(data){
defer.resolve(data); //success... resolve
}, function(error) {
defer.reject(error); //error... reject it
});
return defer.promise; //return the promise
}
return loginService;
}]);

Related

How to get loggedin user info in angularjs

I want to get info on the currently logged in user so that i can display it for example. I have tried the following code but i get the error AuthService.getAuthMember is not a function can anyone help
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http, $cookies) {
// create user variable
var user = null;
// we must create authMemberDefer var so we can get promise anywhere in app
var authenticatedMemberDefer = $q.defer();
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getAuthMember: getAuthMember,
setAuthMember: setAuthMember
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
//this is function that we will call each time when we need auth member data
function getAuthMember() {
return authenticatedMemberDefer.promise;
}
//this is setter function to set member from coockie that we create on login
function setAuthMember(member) {
authenticatedMemberDefer.resolve(member);
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
//**
$cookies.putObject('loginSession', data);
// here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
//on log out remove coockie
$cookies.remove('loginSession');
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
/AuthService.getAuthMember().then(function(member){
console.log(member);
//here your member should be and you can apply any logic or use that data where u want
$scope.username1=member.username;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.text = $scope.username;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
$scope.username = '';
});
}
}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/* var Meetup = $resource('/api/user');
$scope.users = []
Meetup.query(function (results) {
$scope.users = results;
});
*/
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
Meetup.query({text: $scope.text}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
}]);
Can you change your run to something like this
myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
AuthService.setAuthMember(session);
} else {
$location.path('/login');
}
});
});
Also try console.log(AuthService) and check if you see that getAuthMember() function.
Edit:
var myApp = angular.module('myApp', ['ngResource', 'ngRoute', 'ngCookies']);
Don't forget to include angular cookies.

angular spa app not working ngResource

In Angular ngResource is not functionning correctly. I have added the script reference. The problem is that when I add the dependencie to ngResourc blank pages are displayed. What should I do?
/*var app = angular.module('myApp', ['ngResource']);
app.factory('todoFactory', function($resource) {
return $resource('/api/meetups');
});*/
angular.module('myApp').controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
}]);
angular.module('myApp').controller('logoutController',
['$scope', '$location', 'AuthService', '$resource',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
/*
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.afficher = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
*/
$scope.meetups = [];
/*var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}*/
}]);
angular.module('myApp').controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
I will add code on demand
It's always better in such cases to open a debug window (F12 or command+shift+I), toggle Console tab and check what it says. Blank page can de displayed within several circumstances.
Also you can try to complete the commented-out version of your code to avoid new module declaration like this^
var app = angular.module('myApp', ['ngResource']);
app.factory('todoFactory', function($resource) {
return $resource('/api/meetups');
});
app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
}]);
app.controller('logoutController',
['$scope', '$location', 'AuthService', '$resource',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
/*
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.afficher = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
*/
$scope.meetups = [];
/*var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}*/
}]);
app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
angular.module('myApp').controller('logoutController',
['$scope', '$location', 'AuthService', '$resource',
function ($scope, $location, AuthService,**$resource**) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
you havent add the resource to your function

AngularJS - Does not test callback function from Service call in controller in unit test script using Jasmine

Error:In test.js call callback(fetch response) from servie function call in controller
Here there is three files.
In that test.js test the controller.js file using karma-jasmin for unit testing for angular js
controller.js
'use strict';
// Login Angular Module Controller
var loginModule = angular.module('loginModule.controllers'['toaster','vcRecaptcha']);
// Controller Function : loginCtrl
// Parameters : $scope, $rootScope, $cookieStore, $location, AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http, $controller
loginModule.controller('loginCtrl', function ($scope, $rootScope, $cookieStore, $location, AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http, $controller)
{
//redirect user to dashboard if already logged in
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$location.path('/home');
}
// Function Name : forget password
$scope.forgetPassword = function(){
$scope.dataLoading = true;
AuthenticationServiceLogin.forgetPassword($scope.email, function (response) {
if (response.success) {
toaster.pop('success', "", "Email sent Successfully. Please check your email.");
$scope.dataLoading = false;
}else{
toaster.pop('error', "", "Email is incorrect / Email not exist in Database");
$scope.dataLoading = false;
}
});
};
//AuthenticationService.ClearCredentials();
// Function Name : login
$scope.login = function (){
$scope.dataLoading = true;
// callback(response);
// Service Calls Function : userLogin
// Parameters : $scope.username,$scope.password AuthenticationServiceLogin.userLogin($scope.username,$scope.password, function (response) {
console.log(response.success);
if(response.success)
{
AuthenticationServiceLogin.SetCredentials(response);
toaster.pop('success', "", "Login Successful");
$location.path('/home');
}
if (response.status ==200) {
//AuthenticationServiceLogin.SetCredentials(response);
//START STOMP to establish connection
var stompCtrl = $rootScope.$new();
$controller('StompController', { $scope: stompCtrl });
//END STOMP to establish connection
toaster.pop('success', "", "Login Successful");
$location.path('/home');
}
else if(response.status ==401){
toaster.pop('error', response.status+" "+response.statusText," Access is denied due to invalid credentials");
$scope.dataLoading = false;
}
else {
toaster.pop('error', "Username / Password", "Username or password is incorrect");
$scope.dataLoading = false;
}
});
};
});
service.js
'use strict';
var loginModule = angular.module('loginModule.services',['vcRecaptcha']);
loginModule.service('AuthenticationServiceLogin', function ($http, $cookieStore,$rootScope,$timeout, UserService, Base64,vcRecaptchaService,ENV) {
var service = {};
var servicePath = ENV.apiEndpoint;
this.forgetPassword = function(email,callback)
{
$timeout(function () {
var response;
if(email == 'admin#belvms.com'){
response = {success: true};
}
else {
response = {success: false};
}
callback(response);
}, 900);
}
this.userLogin = function(username, password,callback) {
$timeout(function () {
var response;
if(username == 'admin' && password =='admin'){
response = {success: true};
}
else {
//response = {success: false, message: 'Username or password is incorrect'};
}
callback(response);
}, 900);
var data1 = "username=" + username + "&password="
+ password + "&grant_type=password&scope=read%20write&" +
"client_secret=belSecret&client_id=vms-bel";
};
this.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
}
};
});
test.js
'use strict';
describe('Login', function () {
var $controller1,AuthenticationServiceLogin,$window,$scope,$location;
beforeEach(module('loginModule.controllers'));
beforeEach(inject(function(_$controller_,_$q_,_$window_,_$location_) {
$controller1 = _$controller_;
$window = _$window_;
AuthenticationServiceLogin = { userLogin: function() {},
forgetPassword: function() {}
}; spyOn(AuthenticationServiceLogin,'userLogin').and.returnValue(response);
spyOn(AuthenticationServiceLogin,'forgetPassword').and.returnValue(response);
}));
describe('Login', function () {
it('To call Login function', function () {
var $scope = {};
var $rootscope = {};
var $location = {};
var $cookieStore = {};
var $http = {};
var $controller = {};
var FlashService = {};
var controller = $controller1('loginCtrl',{
$scope: $scope,
$rootscope: $rootscope,
$location: $location,
$window: $window,
$cookieStore:$cookieStore,
AuthenticationServiceLogin: AuthenticationServiceLogin,
FlashService:FlashService,
$http:$http,
$controller:$controller
});
$scope.login();
});
it('To call services', function() {
var $scope = {};
var $rootscope = {};
var $location = {};
var $cookieStore = {};
var $http = {};
var $controller = {};
var FlashService = {};
var controller = $controller1('loginCtrl',{
$scope: $scope,
$rootscope: $rootscope,
$location: $location,
$window: $window,
$cookieStore:$cookieStore,
AuthenticationServiceLogin:AuthenticationServiceLogin,
FlashService:FlashService,
$http:$http,
$controller:$controller
});
$scope.username="admin";
$scope.password="admin";
$scope.login();
it('should have a getData function', function() {
expect(angular.isFunction(AuthenticationServiceLogin.userLogin)).toBe(true);
});
$scope.email='admin#belvms.com';
var response1=function(response){};
console.log(response1);
expect(AuthenticationServiceLogin.userLogin).toHaveBeenCalledWith('admin','admin',response1);
});
});
});
Here i attached image that display error when run test script.
enter image description here
so give solution why this erroe or why can't fetch reponse from userLogin function in test script

AngularJS: Trying to use a service, get error "cannot read property 'then' of undefined"

I'm trying to use authenticate with a JWT using my api in Laravel, and it works when I just do the authentication in the controller but I'm trying to do this proper and use a service, however I'm getting an error.
The thing is, when I refresh after the error, it redirects to the dashboard (set that up in app.js), which means a user is authenticated.
What am I doing wrong? Why is it giving me this error?:
TypeError: Cannot read property 'then' of undefined
...it should be redirecting to the 'dashboard' route. The error is at .then(function(data) in the controller.
Here is my service:
(function() {
'use strict';
angular
.module('app')
.factory('userService', ['$http', '$auth', userService]);
function userService($http, $auth) {
var service = {
userLogin: userLogin
};
return service;
function userLogin(credentials) {
$auth.login(credentials)
.then(function() {
$http.get('/api/v1/authenticate/user')
.success(function(res) {
return res;
})
.error(function(error) {
return error;
});
});
};
};
})();
And here is my controller:
(function() {
'use strict';
angular
.module('app')
.controller('LoginController', ['$http', '$rootScope', 'userService', LoginController]);
function LoginController($state, $rootScope, userService) {
var vm = this;
vm.login = login;
vm.error;
function login() {
var credentials = {
email: vm.email,
password: vm.password
};
userService.userLogin(credentials)
.then(function(data) {
if (data) {
var user = JSON.stringify(data.user);
localStorage.setItem('user', user);
$rootScope.currentUser = data.user;
$state.go('dashboard');
} else {
vm.error = error;
}
});
}
}
})();
In the service, you should return a promise if you want to "then" the method. In that service, userLogin method is returning nothing.
You have to pass your service a callback, or use $q.deferred.
function userService($auth, $http) {
return {
userLogin: function(url, credentials, callback) {
$auth.login(credentials).then(function(data) {
$http.get(url).then(function(res) {
callback(res);
});
});
}
};
}
And in your controller
userService("/api/v1/authenticate/user", {password: "pwd", email: "me#me.com"}, function(res) {
res.status; //200
res.data; //whatever you got back from the GET request
});
To be more precise, you're getting cannot read property then of undefined because you're not returning anything to the original invoker. By default javascript will return undefined if nothing is returned, so you get undefined when you try to synchronously return an asynchronous function.
In service you can make use of $q service provided by angular like this
(function() {
'use strict';
angular
.module('app')
.factory('userService', ['$http', '$auth', '$q', userService]);
function userService($http, $auth, $q) {
var service = {
userLogin: userLogin
};
return service;
function userLogin(credentials) {
var deferred = $q.defer();
$auth.login(credentials)
.then(function() {
$http.get('/api/v1/authenticate/user')
.success(function(res) {
// return res;
deferred.resolve(res);
})
.error(function(error) {
// return error;
deferred.reject(error);
});
});
return deferred.promise;
};
};
})();
And in controller you can call the service function as you are currently doing..
(function() {
'use strict';
angular
.module('app')
.controller('LoginController', ['$http', '$rootScope', 'userService', LoginController]);
function LoginController($state, $rootScope, userService) {
var vm = this;
vm.login = login;
vm.error;
function login() {
var credentials = {
email: vm.email,
password: vm.password
};
userService.userLogin(credentials)
.then(function(data) {
if (data) {
var user = JSON.stringify(data.user);
localStorage.setItem('user', user);
$rootScope.currentUser = data.user;
$state.go('dashboard');
} else {
vm.error = error;
}
});
}
}
})();
Hope this helps.

Error: $injector:unpr Unknown Provider in AngularJS

I'm trying to do test app on AngularJS but stuck on few days on one place
with this error:
angular.js:38 Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=AuthtokenProvider%20%3C…terceptor%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile
as I could understand, I did a mistake somewhere in the references:
can you show me where my code below
mainController.js:
angular.module('mainController', [])
.controller('MainController', function($rootScope, $location, Auth) {
var vm = this;
vm.LoggedIn = Auth.isLoggedIn();
$rootScope.$on('$routeChangeStart', function () {
vm.LoggedIn = Auth.isLoggedIn();
Auth.getUser()
.then(function (data) {
vm.user = data.data;
});
});
vm.doLogin = function () {
vm.processing = true;
vm.error = '';
Auth.login(vm.loginData.username, vm.loginData.password)
.success(function (data) {
vm.processing = false;
Auth.getUser()
.then(function (data) {
vm.user = data.data;
});
if (data.success)
$location.path('/');
else
vm.error = data.message;
});
}
vm.doLogout = function () {
Auth.logout();
$location.path('/logout');
}
});
userController.js:
angular.module('userController', ['userService'])
.controller('UserController', function(User){
var vm = this;
User.all()
.success(function (data) {
vm.users = data
})
})
.controller('UserCreateController', function(User, $location, $window){
var vm = this;
vm.signupUser = function () {
vm.message = '';
User.create(vm.userData)
.then(function(response){
vm.userData = {};
vm.message = response.data.message;
$window.localStorage.setItem('token', response.data.token);
$location.path('/');
})
}
})
authService.js:
angular.module('authService', [])
.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};
authFactory.login = function(username, password){
return $http.post('/api/login', {
username: username,
password: password
})
.success(function(data){
AuthToken.setToken(data.token);
return data;
})
}
authFactory.logout = function(){
AuthToken.setToken();
}
authFactory.isLoggedIn = function(){
if(AuthToken.getToken())
return true;
else
return false;
}
authFactory.getUser = function(){
if(AuthToken.getToken())
return $http.get('/api/me');
else
return $q.reject({ message: "User has no token"});
}
return authFactory;
})
.factory('AuthToken', function($window){
var authTokenFactory = {};
authTokenFactory.getToken = function(){
return $window.localStorage.getItem('token');
}
authTokenFactory.setToken = function (token) {
if(token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
}
return authTokenFactory;
})
.factory('AuthInterceptor', function ($q, $location, Authtoken) {
var interceptorFactory = {};
interceptorFactory.request = function(config){
var token = Authtoken.getToken();
if(token){
config.headers['x-access-token'] = token;
}
return config
};
interceptorFactory.responseError = function (response) {
if(response.status == 403)
$location.path('/login');
return $q.reject(response);
}
return interceptorFactory;
});
userService.js:
angular.module('userService', [])
.factory('User', function($http){
var userFactory = {};
userFactory.create = function(userData){
return $http.post('/api/signup', userData);
}
userFactory.all = function(){
return $http.get('/api/users');
}
return userFactory;
});
app.js:
angular.module('MyApp', ['appRoutes', 'mainController', 'authService', 'userController', 'userService'])
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
});
app.routes.js:
angular.module('appRoutes', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/views/pages/home.html'
})
.when('/login',{
templateUrl: 'app/views/pages/login.html'
})
.when('/signup', {
templateUrl: 'app/views/pages/signup.html'
});
//$locationProvider.html5Mode(true);
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
You need to inject your authService into your mainController to make it available since you are using Auth in mainController:
angular.module('mainController', ['authService']);
Everytime you pass in the 2nd argument to module (the array) it creates a new module that doesn't have access to other modules that have been created. So you have to make them available to each other this way.
You can read about loading dependencies here
Maybe the problem is referencing the name of the module in different files. I read in another post here that this makes the module to load the number of times it is repetead. So asign a name to a variable and then use the variable in the rest of the files instead of naming it again.
Example of the forum.

Categories

Resources