AngularJS Type Error - javascript

I am brand new to AngularJS and I'm debugging someone else's code. I am getting the following error when I debug in Google Chrome:
TypeError: accountService.logIn(...).success is not a function.
Here is some of my code. The problem is in the signUp form on the line accountService.logIn(signupform).success(function (response) {. If more info is needed please let me know.
Here is my entire controller.
(function () {
'use strict';
angular
.module('vidaexpress')
.controller('accountController', accountController);
accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];
function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
var vm = this;
vm.logIn = logIn;
vm.signUp = signUp;
vm.signOut = signOut;
vm.facebookLogin = facebookLogin;
vm.facebookLogout = facebookLogout;
vm.recoveryPassword = recoveryPassword;
vm.resetPassword = resetPassword;
vm.sendVerifyEmail = sendVerifyEmail;
function logIn(loginform) {
vm.signinloading = true;
accountService.logIn(loginform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.setUserInfo(response);
if (!$rootScope.returncust) {
window.sessionStorage.setItem('returncust', true);
}
vm.isAccountOpen = false;
}
}, function (error) {
toastr.error(error.error);
}).finally(function () {
vm.signinloading = false;
});
}
function signUp(signupform) {
vm.signuploading = true;
accountService.signUp(signupform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.logIn(signupform).success(function (response) {
accountService.setUserInfo(response);
logIn();
}).error(function(error) {
toastr.error(error.error);
});
}
},function (error) {
toastr.error('System Error');
}).finally(function () {
vm.signuploading = false;
});
}
function signOut() {
//Log out API
//accountService.logOut();
//Log out Facebook
var userInfo = accountService.getUserInfo();
if (userInfo.facebookLogin) {
facebookLogout();
}
//Log out UI
accountService.setUserInfo(null);
vm.isAccountOpen = false;
$state.go('main.index');
}
function facebookLogin() {
facebookService.login();
}
function facebookLogout() {
facebookService.logout();
}
function recoveryPassword(email) {
accountService.recoveryPassword(email).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('An email has been sent.');
}
}, function () {
toastr.error('System Error');
});
}
function resetPassword(model) {
model.customerId = $stateParams.id;
model.token = $stateParams.token;
accountService.resetPassword(model).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Your password has been reset.');
}
}, function () {
toastr.error('System Error');
});
}
function sendVerifyEmail() {
accountService.sendVerifyEmail().then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Email has sent');
}
}, function () {
toastr.error('System Error');
});
}
}
})();
Here is my account.server.js file.
(function () {
'use strict';
angular
.module('vidaexpress')
.service('accountService', accountService);
accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];
function accountService($http, $window, $rootScope, apiUrl) {
var baseUrl = apiUrl.account;
var cookieUser;
var sessionName = 'userInfo';
this.logIn = logIn;
this.logOut = logout;
this.signUp = signUp;
this.setUserInfo = setUserInfo;
this.getUserInfo = getUserInfo;
this.confirm = confirm;
this.recoveryPassword = recoveryPassword;
this.resetPassword = resetPassword;
this.sendVerifyEmail = sendVerifyEmail;
function logIn(credential) {
return $http({
method: 'POST',
url: baseUrl + 'token',
headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
grant_type: 'password',
email: credential.email,
password: credential.password
}
}).then(function (response) {
if (!response) {
return { error: 'System Error' };
} else if (response.error) {
return { error: response.error };
} else {
return response.data;
}
}, function (error) {
return { error: 'System Error' };
});
}
function logout() {
return $http.post(baseUrl + 'logout');
}
function signUp(userInfo) {
return $http.post(baseUrl + 'signup', userInfo);
}
function setUserInfo(userInfo) {
cookieUser = userInfo;
$rootScope.currentUser = userInfo;
$window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
}
function getUserInfo() {
if (!cookieUser) {
cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
}
return cookieUser;
}
function confirm(customerId, token) {
$http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
}
function recoveryPassword(email) {
return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
function resetPassword(model) {
return $http.post(baseUrl + 'resetPassword', model).then(function () {
return null;
}, function(){
return { error: 'System Error' };
});
}
function sendVerifyEmail() {
return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
}
})();

The way your return pattern is working in the service requires your controller to use .then() rather than success()
accountService.logIn(loginform)
.then(function (response) {

Related

Call a method in AccessToken.getCurrentAccessToken() when creating a login in Facebook with React Native

In my app I'm creating a login in Facebook with React Native, and this my code:
async handleFacebookLogin() {
LoginManager.logInWithReadPermissions(['public_profile', 'email', 'user_friends']).then(
function (result) {
if (result.isCancelled) {
console.log('Login cancelled')
} else {
console.log('Login success with permissions: ' + result.grantedPermissions.toString())
AccessToken.getCurrentAccessToken().then(
async (data) => {
let resultChild = await loginWithFaceBook(data.accessToken.toString(), "POST");
if (resultChild.username.length > 0) {
this.loginWithFaceBook(resultChild.token);
}
});
}
},
function (error) {
console.log('Login fail with error: ' + error)
}
)
}
My method:
loginWithFaceBook = async (tokenFace) => {
Toast.show('Login success!');
this.saveTokenLogin(tokenFace);
}
This my error:
_this.loginWithFaceBook is not a function
How to use a method in AccessToken.getCurrentAccessToken() ?
Insert this code:
const _this = this;
to below code:
async handleFacebookLogin() {
and replace this code:
this.loginWithFaceBook(resultChild.token);
by to this code:
_this.loginWithFaceBook(resultChild.token);
Enjoy.
this is full code:
async handleFacebookLogin() {
const _this = this;
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(
function (result) {
if (result.isCancelled) {
console.log('Login cancelled')
} else {
console.log('Login success with permissions: ' + result.grantedPermissions.toString())
let tokenFace = '';
AccessToken.getCurrentAccessToken().then(
async (data) => {
data.accessToken)
let resultChild = await loginWithFaceBook(data.accessToken.toString(), "POST");
if (resultChild.username.length > 0) {
_this.loginFaceBook(resultChild.token);
}
});
}
},
function (error) {
console.log('Login fail with error: ' + error)
}
)
}

what is "error": "unsupported_grant_type" in web Api

I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }

Angular controller structure

I'm a beginner with AngularsJs and I've got a question about the controller structure.
This is my employeeController.js
(function()
{
angular.module('employeeApp').controller('employeeController', employeeController);
function employeeController(employeeFactory,$routeParams,departmentFactory,schoolFactory,mentorFactory,constants,$location,$scope) {
var vm = this;
vm.employee = null;
vm.employees = null;
vm.profilePicture = null;
vm.mentors = null;
vm.schools = null;
vm.departments = null;
vm.roleId = constants.roleid;
vm.internEducators = null;
vm.overviewMentors = function() {
mentorFactory.overview(constants.companyid).then(function(response)
{
vm.mentors = response;
});
}
vm.create = function()
{
employeeFactory.create(vm.employee,vm.profilePicture).success(function(response,status)
{
if(status == 200)
{
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewInternEducators = function() {
employeeFactory.overviewInternEducators(constants.companyid).then(function(response)
{
vm.internEducators = response;
});
}
vm.overviewSchools = function() {
schoolFactory.overview(constants.companyid).then(function(response)
{
if(angular.isDefined(response[0].SchoolId))
{
vm.schools = response;
}
else
{
console.log('leeg!');
}
});
}
vm.overviewDepartments = function() {
console.log('test');
departmentFactory.overview(constants.companyid).then(function(response)
{
vm.departments = response;
});
}
vm.show = function() {
vm.isAdmin = employeeFactory.isAdmin();
employeeFactory.show($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.showDeleted = function() {
employeeFactory.showDeleted($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.update = function()
{
employeeFactory.update(vm.employee, vm.profilePicture).success(function(response, status)
{
if(status == 200)
{
vm.show(); // Zodat de nieuwe afbeelding wordt weergegeven
$.toaster({ message: 'De werknemer is geupdated' });
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewDeleted = function() {
employeeFactory.overviewDeleted().then(function(response)
{
if(angular.isDefined(response[0].EmployeeId))
{
vm.employees = response;
}
});
}
vm.delete = function() {
employeeFactory.delete($routeParams.id).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is verwijderd' });
$location.path('/home');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.permanentDelete = function(employeeId) {
employeeFactory.permanentDelete(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is permanent verwijderd' });
$location.path('/prullenbak/werknemers');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.restore = function(employeeId) {
employeeFactory.restore(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is teruggezet' });
$location.path('/werknemer/' + employeeId);
}
else
{
if(angular.isArray(response))
{
angular.forEach(response, function(error)
{
$.toaster({ priority : 'danger', message : error[0]});
});
}
}
});
}
<!--ng-init-->
vm.editEmployee = function()
{
vm.show();
vm.overviewDepartments();
vm.overviewInternEducators();
vm.overviewMentors();
vm.overviewSchools();
}
vm.createEmployee = function() {
vm.overviewMentors();
vm.overviewSchools();
vm.overviewDepartments();
vm.overviewInternEducators();
}
<!--redirects-->
vm.editRedirect = function(werknemerId)
{
$location.path('/werknemer/edit/' + werknemerId);
}
vm.showTrashedEmployeeRedirect = function(werknemerId)
{
$location.path('/prullenbak/werknemer/' + werknemerId);
}
}
})()
As you can see I use 2 methods called editEmployee and createEmployee (at the end). I use these 2 with the create employee page and the edit employee page. On both pages there are a couple of comboboxes that have to be loaded. In for example my create employee page I say ng-init="employeeController.createEmployee()" and then those comboboxes are filled.
I know this is not the best approach so how could I do this on a different and better way?
There are several ways to structure you app but the style guide endorsed by the Angular team is maintained by John Papa.
Refer to Angular Style Guide by John Papa.
Based on that:
First I would suggest that you split the create, show, edit and delete functionality into separate controllers. This helps with ensuring each controller does only one single thing.This is in line with the idea of Single Responsibility and Separation of Concerns
Secondly since it seems you are using the controllerAs syntax you wouldn't need to inject scope into your controller.
Here is the code for creating an employee(sth like create-employee.controller.js
(function () {
'use strict';
angular.module('employeeApp').controller('CreateEmployeeController', CreateEmployeeController);
//ngInject is used to help create minify safe version of the file during the build process.
//You should have this somewhere in your build process
/** #ngInject **/
function CreateEmployeeController(constants, departmentFactory, employeeFactory, $location, mentorFactory, schoolFactory) {
var vm = this;
vm.create = create;
getMentors();
getSchools();
getDepartments();
getInternEducators();
function getMentors() {
return mentorFactory.overview(constants.companyid).then(function (response) {
vm.mentors = response;
});
}
function getSchools() {
return schoolFactory.overview(constants.companyid).then(function (response) {
if (angular.isDefined(response[0].SchoolId)) {
vm.schools = response;
}
else {
console.log('leeg!');
}
});
}
function getDepartments() {
return departmentFactory.overview(constants.companyid).then(function (response) {
vm.departments = response;
});
}
function getInternEducators() {
return employeeFactory.overviewInternEducators(constants.companyid).then(function (response) {
vm.internEducators = response;
});
}
}
function create() {
return employeeFactory.create(vm.employee, vm.profilePicture).success(function (response, status) {
if (status == 200) {
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function (response) {
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function (error) {
if (i <= 2) {
$.toaster({priority: 'danger', message: error});
}
i++;
});
});
}
})();
You would then create the other controllers by splitting the functionality following this example.

Value of var goes back to empty after exiting function?

So I have an api request inside of a function thats placed in my Service script.. I have defined the variable "curruser" outside of the function so I can keep its value, however after exiting the follow Scirpt, curruser is empty??
services.js
function fbUserInfo() {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
So the console.log would return the proper JSON object I retrieved from facebook.. but when I return it in the return statement
return {
userInfo: function() {
fbUserInfo();
console.log(curruser);
return curruser;
}
it returns that curruser is an empty object! I did write
var curruser;
into the first line inside the ".factory"
you have to use then() since fbUserInfo() is async function
return {
userInfo: function() {
$.when(fbUserInfo())..then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
}).then(function(){
console.log(curruser);
return curruser;
})
}
Haven't tested this but might work.
var curruser;
function fbUserInfo( callback ) {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
callback(curruser);
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
return {
userInfo: function( callback ) {
fbUserInfo( function(data){
console.log(data);
callback(data);
});
}

Getting an Error in AngularJS Post 404 Bad Request Error

I am brand new to AngularJS and I'm pretty lost. On submitting a form I'm getting the error message: POST http://prerelease.vidaexpress.com/api/account/token 400 (Bad Request). The error happens when I try to submit the form. Maybe someone can help me. Part of my service is below:
(function () {
'use strict';
angular
.module('vidaexpress')
.service('accountService', accountService);
accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];
function accountService($http, $window, $rootScope, apiUrl) {
var baseUrl = apiUrl.account;
var cookieUser;
var sessionName = 'userInfo';
this.logIn = logIn;
this.logOut = logout;
this.signUp = signUp;
this.setUserInfo = setUserInfo;
this.getUserInfo = getUserInfo;
this.confirm = confirm;
this.recoveryPassword = recoveryPassword;
this.resetPassword = resetPassword;
this.sendVerifyEmail = sendVerifyEmail;
function logIn(credential) {
return $http({
method: 'POST',
url: baseUrl + 'token',
headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
grant_type: 'password',
email: credential.email,
password: credential.password
}
}).then(function (response) {
if (!response) {
return { error: 'System Error' };
} else if (response.error) {
return { error: response.error };
} else {
return response.data;
}
}, function (error) {
return { error: 'System Error' };
});
}
function logout() {
return $http.post(baseUrl + 'logout');
}
function signUp(userInfo) {
return $http.post(baseUrl + 'signup', userInfo);
}
function setUserInfo(userInfo) {
cookieUser = userInfo;
$rootScope.currentUser = userInfo;
$window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
}
function getUserInfo() {
if (!cookieUser) {
cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
}
return cookieUser;
}
function confirm(customerId, token) {
$http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
}
function recoveryPassword(email) {
return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
function resetPassword(model) {
return $http.post(baseUrl + 'resetPassword', model).then(function () {
return null;
}, function(){
return { error: 'System Error' };
});
}
function sendVerifyEmail() {
return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
}
})();
Here is my controller:
(function () {
'use strict';
angular
.module('vidaexpress')
.controller('accountController', accountController);
accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];
function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
var vm = this;
vm.logIn = logIn;
vm.signUp = signUp;
vm.signOut = signOut;
vm.facebookLogin = facebookLogin;
vm.facebookLogout = facebookLogout;
vm.recoveryPassword = recoveryPassword;
vm.resetPassword = resetPassword;
vm.sendVerifyEmail = sendVerifyEmail;
function logIn(loginform) {
vm.signinloading = true;
accountService.logIn(loginform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
vm.login = {};
vm.submit = false;
accountService.setUserInfo(response);
if (!$rootScope.returncust) {
window.sessionStorage.setItem('returncust', true);
}
vm.isAccountOpen = false;
}
}, function (error) {
toastr.error(error.error);
}).finally(function () {
vm.signinloading = false;
});
}
function signUp(signupform) {
vm.signuploading = true;
accountService.signUp(signupform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.logIn(signupform).then(function (response) {
accountService.setUserInfo(response);
$state.go('main.index');
}, function(error) {
toastr.error(error.error);
});
}
},function (error) {
toastr.error('System Error');
}).finally(function () {
vm.signuploading = false;
});
}
function signOut() {
//Log out Facebook
var userInfo = accountService.getUserInfo();
if (userInfo.facebookLogin) {
facebookLogout();
}
//Log out UI
accountService.setUserInfo(null);
vm.isAccountOpen = false;
$state.go('main.index');
}
function facebookLogin() {
facebookService.login().then(function (response) {
if (response.status == 'connected' && $state.current.name == 'landing.index') {
$state.go('main.index');
} else {
vm.isAccountOpen = false;
}
});
}
function facebookLogout() {
facebookService.logout();
}
function recoveryPassword(email) {
accountService.recoveryPassword(email).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('An email has been sent.');
}
}, function () {
toastr.error('System Error');
});
}
function resetPassword(model) {
model.customerId = $stateParams.id;
model.token = $stateParams.token;
accountService.resetPassword(model).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Your password has been reset.');
}
}, function () {
toastr.error('System Error');
});
}
function sendVerifyEmail() {
accountService.sendVerifyEmail().then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Email has sent');
}
}, function () {
toastr.error('System Error');
});
}
}
})();
And here is my view:
<form class="form" name="loginform" ng-submit="loginform.$valid && vm.logIn(vm.login)" novalidate>
<div class="form-group">
<label for="email">{{'USERNAME' | translate}} ({{'EMAIL' | translate}})</label>
<input id="email" name="email" class="form-control" required ng-model="vm.login.email" ng-focus="vm.loginerror = '';" ng-pattern="/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z0-9]{2,6}$/">
<div class="error_msg" ng-show="loginform.email.$error.required && vm.submit">{{ 'EMAIL_ENTER' | translate }}</div>
<div class="error_msg" ng-show="loginform.email.$error.pattern && vm.submit">{{ 'EMAIL_ERROR_PATTERN' | translate }}</div>
</div>
<div class="form-group">
<label for="password">{{'PASSWORD' | translate}}</label>
<input id="password" name="password" type="password" class="form-control" required ng-model="vm.login.password" ng-focus="vm.loginerror = '';">
<div class="error_msg" ng-show="loginform.password.$error.required && vm.submit">{{ 'PASSWORD_ENTER' | translate }}</div>
</div>
<div class="form-group">
<div class="error_msg">{{vm.loginerror}}</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary button_dkblue" ng-click="vm.submit=true;" ng-disabled="vm.signinloading" ve-btn-loading>{{'SIGN_IN' | translate}}</button>
</div>
<span><a ui-sref="password.recovery" ng-click="vm.isAccountOpen=false">{{ 'FORGOT_PASSWORD' | translate }}</a></span>
It's error from server side ,status code 404 means "NOT FOUND". The resources are not present which you are request for,so please check your token also it's correct or not
This is most likely coming from the URL you are posting to. Can you check the script you are sending this to? 404 isn't a javascript error, but where you are posting it to.

Categories

Resources