How to get loggedin user info in angularjs - javascript

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.

Related

I'm unable to get my Angular Service to connect

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;
}]);

Undefined when returning $http promise in controller from factory

No matter what I do I always get $$state or undefined back from my factory API call. I've tried promises and simply returning response.data from .then but nothing I tried works.
I can get the proper response data into my controller but then when I try to assign it to anything I just get undefined or $$state, depending on which method I use.
My factory:
factory('forecastFactory', function ($http, $q, SundialConfig) {
var Forecast = {};
var weatherKey = SundialConfig.openWeatherKey;
Forecast.dayCnt = 1;
Forecast.prepareCity = function (city) {
city === undefined ? city = 'Chicago, IL' : city = city;
return city;
}
Forecast.getForecast = function (city) {
var preparedCity = Forecast.prepareCity(city);
var deferred = $q.defer();
$http.jsonp('http://api.openweathermap.org/data/2.5/forecast/daily?', {
params: {
appid: weatherKey,
q: preparedCity,
cnt: Forecast.dayCnt,
callback: 'JSON_CALLBACK'
}
})
.then(function (res) {
console.log("success");
deferred.resolve(res);
})
.catch(function (err) {
console.log('error');
});
return deferred.promise;
}
return Forecast;
});
My controller:
controller('ForecastController', function ($scope, $location, forecastFactory, locationService) {
vm = this;
forecastFactory.getForecast('Chicago, IL').then(function (res) {
console.log(res);
vm.forecast = res;
});
});
I think you don't need to use $q because $http returns a promise,
you can do
Forecast.getForecast = function(city) {
var preparedCity = Forecast.prepareCity(city);
return $http.jsonp('http://api.openweathermap.org/data/2.5/forecast/daily?', {
params: {
appid: weatherKey,
q: preparedCity,
cnt: Forecast.dayCnt,
callback: 'JSON_CALLBACK'
}
})
.then(function(res) {
console.log("success");
return res.data;
})
.catch(function(err) {
console.log('error')
return []; // or {} depending upon required data
});
}
and in controller, do the same as you are doing now
Other way is simply return the promise returned by $http
Forecast.getForecast = function(city) {
var preparedCity = Forecast.prepareCity(city);
return $http.jsonp('http://api.openweathermap.org/data/2.5/forecast/daily?', {
params: {
appid: weatherKey,
q: preparedCity,
cnt: Forecast.dayCnt,
callback: 'JSON_CALLBACK'
}
})
}
and in controller do this
Sundial.Controllers.
controller('ForecastController', ['$scope', '$location', 'forecastFactory', 'locationService', function($scope, $location, forecastFactory, locationService) {
vm = this;
forecastFactory.getForecast('Chicago, IL').then(function(res) {
console.log(res)
vm.forecast = res.data;
}, function(err){
// do something
})
}]);

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.

AngularJS - how to update variable on $scope after JSON returns

I'm new in angular and I'm working on a project that depends on service and factories. my problem is when I'm using a static jason array for response, the variables are filled correctly and are shown in view, but when I change it to a ajax request and get it from a json file, the response comes successful but the controller variables are not successfully loaded with data.
this is my angular project structure:
'use strict';
angular
.module('mytestapp',['ngRoute'])
.config(config)
.controller('HomeCtrl', HomeCtrl)
.controller('AboutCtrl', AboutCtrl)
.factory('GeneralInit', GeneralInit)
.service('UserSrv', UserSrv);
GeneralInit.$inject = ['UserSrv','$q'];
HomeCtrl.$inject = ['GeneralInit','$timeout','UserSrv'];
and here are my config:
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'template/home.html',
controller: 'HomeCtrl',
controllerAs: 'hmc',
resolve: {
GeneralInit: function(GeneralInit){
return GeneralInit();
}}
})
.when('/about', {
templateUrl: 'template/about.html',
controller: 'AboutCtrl',
controllerAs: 'abc',
resolve: {
GeneralInit: function(GeneralInit){
return GeneralInit();
}}
});
}
here is my service:
function UserSrv($http) {
var User={};
var service = {
getUser: Get,
updateUser: Update,
logoutUser: Logout
};
return service;
function Get() {
//return {"FirstName":"StaticName","LastName":'StaticLastName'}
$http.get('/user.json')
.success(function(data, status, headers, config) {
User = data;
console.log(User);
return User;
})
.error(function(data, status, headers, config) {
})
}
function Update() {
}
function Logout() {
}
}
My controller and initialize item:
function GeneralInit(UserSrv,$q)
{
return function() {
var User = UserSrv.getUser(); //{'FirstName':'FstName','LastName':'LstName'};//
var Base='browser';
return $q.all([User, Base]).then(function(results){
return {
User: results[0],
Base: results[1]
};
});
}
}
function HomeCtrl(GeneralInit,$timeout)
{
var hmc= this;
$timeout(function(){
hmc.User=GeneralInit.User;
console.log(hmc.User);
}
,0);
}
The reason why you don't see any data in the console.log(hmc.User); statement is because by the time this statement executes, the promise is not actually resolved (the request fetching users has not yet returned). Though digest cycle is invoked as a result of using $timeout, hmc.User does not have data yet.
Try invoking the digest cycle after the requests actually return in your GeneralInit method, and you should have the data available.
And also you should probably change your Get method to return a promise:
function UserSrv($http) {
var User = {};
var service = {
getUser: Get
};
return service;
function Get() {
return $http.get('/user.json')
.success(function(data, status, headers, config) {
User = data;
console.log(User);
return User;
})
.error(function(data, status, headers, config) {
})
}
}
Your GeneralInit function is expecting getUser to return a promise, so just change it to this:
function UserSrv($http, $q) {
var User={};
var service = {
getUser: Get,
updateUser: Update,
logoutUser: Logout
};
return service;
function Get() {
var deferred = $q.defer();
//return {"FirstName":"StaticName","LastName":'StaticLastName'}
$http.get('/user.json')
.success(function(data, status, headers, config) {
User = data;
console.log(User);
deferred.resolve(user);
return User;
})
.error(function(data, status, headers, config) {
});
return deferred.promise;
}
}

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