$scope changes in .success() not applying - javascript

Parse.User.logIn($scope.user.username, $scope.user.password, {
success: function (user) {
console.log("logged in");
$scope.User = user;
$scope.$apply();
},
error: function (user, error) {
console.log(error);
}
})
In the view, I have {{User.attributes.username}} that right after login shows nothing, but when someones already logged in and views the page, it works fine.
The scope doesn't change when someone just logs in. But above, I already have $scope.User = Parse.User.current() and that works fine. It seems to be an issue with this particular instance of changing the scope.

Try this:
success: function (user) {
console.log("logged in");
$scope.$apply(function() {
$scope.User = user;
});
},

Related

how show response data in other page angularjs

Using the code snippet below I'm authenticating email, password. The customerlogin() method returns some JSON data which I want to show in the next page. In other words I want to pass the data returned from customerlogin() to then() and then pass it to /customerprofile
Please help
login(form) {
this.submitted = true;
if (form.$valid) {
this.Auth.customerlogin({
email: this.operator.email,
password: this.operator.password
})
.then(() => {
// Logged in, redirect to home
this.$location.path('/customerprofile');
})
.catch(err => {
this.errors.login = err.message;
});
}
}
//Other file Auth.js
customerlogin({
email,
password
}, callback) {
console.log('Customer Authentice Method');
return $http.post(properties.customer_login, {
email, password
})
.then(res => {
properties.GetId = res.data.id;
$cookies.put('token', res.data.token);
currentUser = User.get();
return currentUser.$promise;
})
.then(user => {
safeCb(callback)(null, user);
return user;
})
.catch(err => {
Auth.logout();
safeCb(callback)(err.data);
return $q.reject(err.data);
});
}
i want show data these textbox
enter image description here
Your login function should be calling a service method which makes the ajax call and stores the response as an object property on that service. The controller then has that on scope because you've injected the service. There's nothing to pass. It's already there and is watched automatically by Angular.
Something like this:
angular.someModule('someModule')
.service('someService', function($http) {
return {
loginCall: function(...) {
// do ajax call here
return loginStuff; // must be an object (or wrapped in one)
}
};
})
.controller('SomeController', ['someService', function(someService) {
var sc = this; // controllerAs syntax
sc.login = function(form) {
someService.customerlogin(...).then(...).catch(...);
// because someService has been injected, someService.loginCall is now
// available and being watched by the controller, on its scope...
// and can be used in your view like {{someService.loginCall.dataProperty}}
...
};
}]);
There are probably some missing pieces here (module injections), but this should get you started.
At first, try to use this construction for your .then:
.then(function (data) {
$log.debug(data); //to console log passed data via angular
});

MEAN.io Strange $http.get Response

I am trying to develop a user management feature for a website using the MEAN.io stack. What I'm trying to do has worked in the past for other models on the same site so I'm not sure what is going on. My issue is that I am trying to get all the User models from the MongoDB database and pass them to an AngularJS controller so that I can display their information on a user management page. To that end, I added this function to the User controller in the backend:
exports.readUsers = function(req, res) {
var decodedToken = req.decodeToken;
var User = mongoose.model('User');
var id = req.params.id;
existUser(decodedToken, function(err, user) {
if(err) {
return sendError(res, 'INVALID_TOKEN');
}
User.find({})
.select('username')
.exec(function(err, results) {
if(err) {
return sendError(res, err);
}
res.json({success: true, userList: results});
});
});
}
This line to the routing code:
router.get('/users/all', Authorization.token, user.readUsers);
And this AngularJS controller for use with the frontend:
(function () {
"use strict";
var app = angular.module("GAP");
app.factory("UserEditFactory", function UserEditFactory($http, API_URL, AuthTokenFactory, $q) {
"use strict";
return {
readUsers: readUsers
};
//Get all users in the DB
function readUsers() {
if(AuthTokenFactory.getToken()) {
return $http.get(API_URL + "/users/all");
}else {
return $q.reject({
data: "valid token required"
});
}
}
});
app.controller("userPageController", ["UserEditFactory", "$scope", "$http", "$window", "API_URL",
function(UserEditFactory, $scope, $http, $window, API_URL) {
UserEditFactory.readUsers().then(function(data) {
console.log(data.data);
$scope.users = data.data.userList;
}, function(response) {
console.log(response);
});
}
]);
})();
When I load the page that is supposed to display this information, no data is displayed. I have determined that the AngularJS controller is calling the second function which I understand is the one used to respond to an error.
Further investigation of the object returned by the $http.get call reveals no data, and a status of -1. I'm not sure why this is happening, because I have used this exact pattern of code to get and display data from other models in the database on the same site. I can manually make HTTP calls to those working functions from this controller, and everything works fine. I'm not sure where to go from here or how to learn more about the issue. Can anyone offer insight? Let me know if you need more information.
Edit: As requested, here is the code for the AuthTokenFactory, which is an app.factory object in a common JS file.
app.factory('AuthTokenFactory', function AuthTokenFactory($window) {
'use strict';
var store = $window.localStorage;
var tokenKey = 'auth-token';
var userKey = "username";
return {
getToken: getToken,
setToken: setToken,
setUsername: setUsername
};
function getToken() {
return store.getItem(tokenKey);
}
function setToken(token) {
if (token) {
store.setItem(tokenKey, token);
} else {
store.removeItem(tokenKey);
}
}
function setUsername(username) {
if (username) {
store.setItem(userKey, username);
} else {
store.removeItem(userKey);
}
}
});

Getting error Firebase. createUser failed: First argument must contain the key "password" Angularjs

I'm new to angular and I'm following a chatapp tutorial from online. I'm getting this the error "Firebase.createUser failed: First argument must contain the key "password" " when I try to register with an email and password. The app isn't complete yet, I just finished the auth part. Google answers suggested that I update to the latest angularfire, which I did ( 1.1.3). No idea what to do.
Register state in app.js:
.state('register', {
url: '/register',
templateUrl: 'auth/register.html',
controller:'AuthCtrl as authCtrl',
resolve:{
requireNoAuth: function($state,Auth){
return Auth.$requireAuth()
.then(function(auth){
$state.go('home');
},
function(error){
return;
});
}
}
})
authController.js
angular.module('chatApp')
.controller('AuthCtrl', function (Auth, $state) {
//Using 'Controller as syntax', instead of $scope, we use 'this' to make controller
var authCtrl = this;
//user object controller
authCtrl.user = {
email:'',
pass:''
};
//login object controller. Firebase provides functions. Using promises. ( either it's fufilled, or rejected)
authCtrl.login = function () {
Auth.authWithPassword(authCtrl.user)
// .then takes in 2 parameters( onSuccess, onFaliure)
//if successfull, go home
.then(function (auth) {
$state.go('home');
},
//if failed, set error in controller, so we can call it and display message later
function (error) {
authCtrl.error = error;
});
};
//registering user
authCtrl.register = function () {
Auth.$createUser(authCtrl.user)
// prompt user to login if successful
.then(function (user) {
authCtrl.login();
},
//else bring up error
function (error) {
authCtrl.error = error;
})
}
});
authFactory.js
angular.module('chatApp')
.factory('Auth',function($firebaseAuth,FirebaseUrl){
var declare= new Firebase(FirebaseUrl);
var auth=$firebaseAuth(declare);
return auth
});
It's password, not pass.
Secondly, you're incorrectly resolving the user in your route config. Rather than using the promise chain in resolve, you just need to return the promise.
.state('register', {
url: '/register',
templateUrl: 'auth/register.html',
controller:'AuthCtrl as authCtrl',
resolve:{
requireNoAuth: function($state,Auth){
return Auth.$requireAuth(); // return the promise
}
}
})
Then in the run() phase, you can listen for routing errors:
app.run(function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
if (error === "AUTH_REQUIRED") {
$location.path("/home");
}
});
});
Check out the AngularFire docs on using Auth with Routing for more information.

AngularFire (Angular + Firebase) Authentication Error delay

I found out something weird. Please help!
$scope.login = function() {
ref.authWithPassword({
email: $scope.user.email,
password: $scope.user.password
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
$scope.message = error.toString();
} else {
$location.path('/meetings');
console.log("Authenticated successfully with payload:", authData);
}
});
} //login
This is a login function and it works nicely.However, the thing is that I get error 3, 4 sec after I have submitted the login. I noticed that my {{message}} is not being updated immediately after I receive value at $scope.message . I thought Angular should show that value as soon as it changes. ?
After I click for the second time, I get the error showed.
This is where I am printing the value:
<p class="error formerror" ng-show="message">{{message}}</p>
You're calling authWithPassword, which is part of Firebase's regular JavaScript SDK. This API will start the authentication process and call your function when the authentication completes. Unfortunately at that point AngularJS is no longer aware of any updates you make to $scope.
To make AngularJS aware of the update, wrap your code in a $timeout call:
$scope.login = function() {
ref.authWithPassword({
email: $scope.user.email,
password: $scope.user.password
}, function(error, authData) {
$timeout(function() {
if (error) {
console.log("Login Failed!", error);
$scope.message = error.toString();
} else {
$location.path('/meetings');
console.log("Authenticated successfully with payload:", authData);
}
});
});
} //login
Note that precisely for this reason, AngularFire provides convenience wrappers around these authentication functions in its $firebaseAuth service. See the section in the AngularFire guide on logging users in.
The wrapper function you're looking for is $authWithPassword, read a sample of how to use $authWithPassword in its API documentation.

Parse User.Login never gets called?

I'm simply trying to Log in with a user I've just created in Parse.
I know the user is valid, I know the function gets called.
This is what I tried:
// V1
Parse.User.logIn("username", "password").then(function(user) {
console.log("Logged in");
}, function(error) {
console.log("Error logging in");
});
// V2
Parse.User.logIn("username", "password", {
success: function(user) {
console.log("Logged in");
},
error: function(user, error) {
console.log("Error logging in");
}
});
And neither of the console logs show up, success or failure...
Is there something I'm missing?
Thanks!
This was in fact due to the asynchronous nature of the Parse.User.Login code, had to work with it as a promise
For others having this issue: http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/

Categories

Resources