how show response data in other page angularjs - javascript

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

Related

AngularFire $save() not a function

I've seen other posts about problems with $save(), but I couldn't relate it to my code. I have a profile controller with an updateProfile() method that ultimately attempts to save the new data to the database after it has been changed.
I have defined my profile controller as follows:
angular.module('angularfireSlackApp')
.controller('ProfileCtrl', function($state, md5, profile) {
var profileCtrl = this;
var currentUser = firebase.auth().currentUser;
profileCtrl.profile = profile;
// Retrieves the user's email from input field, hashes it, and saves the data to the database
profileCtrl.updateProfile = function() {
console.log(profileCtrl.profile); // Profile object exists and is populated as expected
profileCtrl.profile.emailHash = md5.createHash(currentUser.email);
profileCtrl.profile.$save();
}
});
My user service:
angular.module('angularfireSlackApp')
// Provides a means of retrieving User data or list of all Users
.factory('Users', function($firebaseArray, $firebaseObject) {
// Provides a means of retrieving User data or list of all Users
// Create a reference to users that can be used to retrieve an array of users
var usersRef = firebase.database().ref("users");
users = $firebaseArray(usersRef);
var Users = {
// Returns a firebase object of a specific user's profile
getProfile: function(uid) {
return $firebaseObject(usersRef.child(uid));
},
// Returns the display name of a specific user
getDisplayName: function(uid) {
return users.$getRecord(uid).displayName;
},
// Returns the Gravatar url that corresponds to the user
getGravatar: function(uid) {
return 'www.gravatar.com/avatar/' + users.$getRecord(uid).emailHash;
},
// Returns a firebase array of users
all: users
};
return Users;
});
Profile state from main app:
.state('profile', {
url: '/profile',
controller: 'ProfileCtrl as profileCtrl',
templateUrl: 'users/profile.html',
resolve: {
auth: function($state) {
firebase.auth().onAuthStateChanged(function(user) {
if (user == null) {
$state.go('home');
console.log("In auth but user NOT valid");
} else {
console.log("In auth and user valid");
}
});
},
profile: function(Users) {
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log("In profile and user valid");
return Users.getProfile(user.uid).$loaded();
} else {
console.log("In profile but user NOT valid");
}
});
}
}
});
console.log:
For some reason I'm getting an error that profileCtrl.profile.$save() is not a function. I know that the profileCtrl.profile object is legitimate and that I'm using $save() appropriately, but I just can't figure out what else could be the problem.
My gut feeling is that I'm missing something simple, but I'm brand new to AngularJS and Firebase so I wouldn't be surprised.
In the resolve of your "profile" state you are not returning anything.
You should fix it to:
auth: function($state, $firebaseAuth) {
return $firebaseAuth().$onAuthStateChanged().then(function(user) {
if (!user) {
$state.go('home');
console.log("In auth but user NOT valid");
} else {
console.log("In auth and user valid");
}
}); // classic situation to use $requiresAuth()
},
profile: function(Users, $firebaseAuth) {
return $firebaseAuth().$requireSignIn();
}
Moreover, your service shouldn't keep the reference to the $firebaseArray but create it for each controller that wants to use it.
The down-side is you'll have to make some changes, but the up-side is a more predictable, maintainable code:
var Users = {
// Returns a firebase object of a specific user's profile
getProfile: function(uid) {
return $firebaseObject(usersRef.child(uid));
},
// Returns the display name of a specific user
getDisplayName: function(uid) {
// This is actually an issue to get the name synchronously, but I see no reason why not using the Firebase SDK and fetch a-sync
//return users.$getRecord(uid).displayName;
return usersRef.child(uid)
.child('displayName')
.once('value')
.then(function (snap) {
return snap.val();
});
},
// Returns the Gravatar url that corresponds to the user
getGravatar: function(uid) {
// Again fetch a-synchronously
//return 'www.gravatar.com/avatar/' + users.$getRecord(uid).emailHash;
return usersRef.child(uid)
.child('emailHash')
.once('value')
.then(function (snap) {
return 'www.gravatar.com/avatar/' + snap.val();
});
},
// Returns a firebase array of users
all: function () {
return $firebaseArray(usersRef);
}
};
Also refer to the new AngularFire docs: API reference

TypeError: Cannot set property 'firstData' of undefined

IM getting two errors in my service. They are both the same errors. IM going to post my service and my controller.
This is my service:
getData: function (dataRecievedCallback, schemeid, userid) {
//Average JSON api
averageData = function () {
return $http.get(first.json)
}
//User JSON api
userData = function () {
return $http.get(second.json)
}
And here is my controller:
serviceName.averageData().then(function (response) {
$scope.firstData = response.data;
});
serviceName.userData().then(function (response) {
$scope.secondData = response.data;
});
I dont want to elaborate my data I want to display it as it is. In my html I have an ng-repeat, how can I add both in my expression?
Here is an example to show how this should be set up:
Service:
methodName: function() {
return $http.get(first.json);
}
Controller:
ServiceName.methodName().then(function(response) {
$scope.firstData = response.data;
}).catch(function(error) {
console.log(error); // See the error in console if any
});

How to retrieve data from api res.send?

I am using the javascript MEAN stack for my single page app.
I have an Angular factory making a call to my Api.
app.factory('authorizing', function($resource){
return $resource(
'/api/authorizing/:username',
{'username':'#username'},
// retreiving only one user and all their roles
{'singleUser' : {
method:'GET'
,isArray: false
}}
);
});
I call the factory in my controller like this. My goal is to update the web page data based on the response I get back from the Api. I expect a true or false value to be returned. I have tried other things but I want to keep my authorization on the server side.
app.controller('usrPageController', function ($scope, usrServiceById, $route, authorizing, $rootScope) {
$scope.updateUser = function (data,field){
var vCheckUserRoles;
vCheckUserRoles = authorizing.singleUser({'username': $rootScope.current_user});
if (vCheckUserRoles == true){
usrServiceById.update({'username':username},{field:data, 'fieldName':field});
};
};
});
The database returns the result data using a res.send.
.get(function (req, res) {
RoleUser.find({ 'aclUserName': req.params.username }, function (err, aclUser) {
if (err) { return res.sendStatus(500) };
// return an error if no user is found
if (aclUser == null) { return res.sendStatus(401) };
//check for proper role in list of users
for (var i = 0; i < aclUser.length; i++) {
if (aclUser[i].aclUserResource == req.params.username + '_PROFILE') {
//return a successful status
return res.send('true');
};
};
//return a failed status
return res.send('false');
});
});
I don't get any errors from the code but the return object is empty when it hits the controller after the res.send. I have tried different types of data to return but nothing seems to work for me. Any help is appreciated. I have othe res.send calls in my Api. They work but I take the data directly from my database wiht the callback and feed it to the res.send. This is the only time in my code that I am trying to return something besides the successful callback variable.
UPDATED CODE:
I removed the var vCheckUserRoles. Now the value is passed to a success callback
app.controller('usrPageController', function ($scope, usrServiceById, $route, authorizing, $rootScope) {
authorizing.singleUser({'username': $rootScope.current_user},function(response){
console.log('response = ' + response.data)
if (response.data == 'true'){
usrServiceById.update({'username':usrSingle.username},{field:data, 'fieldName':field});
};
});
});
You can use res.json instead of res.send to send status of your query.
Example ////
res.json({status:true})
And on client side you can access that status value in data.status field.
On the server you send data as follows:
res.status(200).send({message: "Hello!"});
In the front-end you receive the data, then resolve it to get data as follows:
fetch(url)
.then(response => {
if(response.ok) {
return response.json();
}
}).then(data => {
if(data) {
console.log(data);
}
}).catch(err => console.error(err));

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.

Categories

Resources