How can I get specific value from $http.get in AngularJS - angularjs

I have a simple question. When I use $http.get in angular controller, how can I use a specific value from the results? Let's say that I am getting username and password and I want to compare each one individually.
app.controller("loginController", function ($scope, $http) {
$scope.submit = function () {
$http.get("../Views/userAuthentecation.aspx")
.then(function (response) {
$scope.members = response.data;
});
}
});
From the above controller, I am using the userAuthentecation.aspx to read from database in the behind code and just display the results as json format. So, the $scope.members is actually a json format data contains username and password.

Well generally we assign an entire response to a single object like you did
$scope.members = response.data;
but lets say if you have 3 objects in response.data and you want them all to be in the different objects than you can simply assign them to different objects like below
$scope.id = response.data.id;
$scope.username = response.data.username;
$scope.members = response.data.password;
once the data is assigned to $scope.objects than you can do with it whatever you like but Since you have authentication code in your controller i suppose you are trying to make an authentication system. well in that case once the login form is filled its been send to a function in controller for authentication for example
<form name="form" ng-submit="login()" role="form">
once the controller gets the request you can either process it in the same function or you can send it to authentication service which is usually a factory to perform a specific task in this case it will check the user crediantials.
$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function(response) {
if(response.success) {
AuthenticationService.SetCredentials($scope.username, $scope.password);
$location.path('/');
} else {
$scope.error = response.message;
$scope.dataLoading = false;
}
});
};
the above function is calling another factory for authenticating the user credentials, the factory AuthenticationService will be called which will pass the parameters to Login() function. function within the factory can be called like this
AuthenticationService.login()
once the credentials are checked and verfied and response code is 200 which means ok then entered creditals will be passed to
AuthenticationService.SetCredentials($scope.username, $scope.password);
which will generated encrypted cookie
hope this will give a little understand about authentication and comparing the response data, the entire workig authentication example can be found here

Related

Injecting data to controller with a spinner

I have a SocketService (using socket.io) and I make a call to my backend server like so:
SocketService.on("get user data", (response) => {
DataService.data = response;
});
I have a controller like so:
...
.controller("UserController", ($scope, DataService) => {
SocketService.emit("get user data");
$scope.users = DataService.data;
});
Now, this is the flow:
Controller loads, makes a request to our backend using SocketService.
$scope.users becomes equal to an empty array since we didn't get a response yet.
SocketService listens for the response, updates DataService.
The problem is, unless I click the button to load UserController again, I see an empty array. So, first click, I see an empty array. Second click after 1 seconds, I see the users array.
Is there any way to do something like this on Angular?
// pseudo code
SocketService.emit("get user data");
Spinner.show();
SocketService.on("get user data", (response) => {
angular.controllers.resolve("UserController", ($scope) => {
$scope.users = response;
});
Spinner.hide();
});
I don't know your SocketService with socket.io, but if it were a normal angular service and call the backend via $http i would do following:
SocketService (inject $http):
function get(url, config) {
return $http.get(url, config);
};
UserController (inject your SocketService):
function getUserData() {
SocketService.get('myUrl', {})
.then(function(response) {
$scope.users = response.data;
});
}
I hope this give you an impulse to solve your problem.

How to post some data and get results using MEAN stack and ngResource

I am working on a application and I am using MEAN stack as technology. In AngularJS, I am using ngResource to CRUD operations. Can any one suggest how to send username and password to server and get response back to check if the credentials are valid. I need help in ngResource and mongoose code. Thanks.
Check out the mean.js boilerplate:
https://github.com/meanjs/mean
You'll see how they do it pretty quickly:
moduleName.client.controller.js will make an http call, using the injected http. Here is an example of the call being made from /modules/users/client/controllers/authentication.client.controller.js (with some edits to the code to make it easier to see what you're looking for):
AuthenticationController.$inject = ['$scope', '$state', '$http', 'Authentication'];
function AuthenticationController($scope, $state, $http, Authentication, ) {
...
vm.authentication = Authentication;
$http.post('/api/auth/signup', vm.credentials).success(function (response) {
// If successful we assign the response to the global user model
vm.authentication.user = response;
}).error(function (response) {
vm.error = response.message;
});
}
Now, this call is posted to '/api/auth/signup'. The file that handles this route is located in /modules/users/server/routes/auth.server.routes.js:
modules.exports = function(app) {
var users = require('../controllers/users.server.controller');
...
app.route('/api/auth/signup').post(users.signup);
}
As you can see, the route (the url) matches the one you called from the client controller. As that $http call from the controller was a $http.post(), the route entry must match. You can see that it does above.
The parameter users.signup passed above refers to a function in yet another file: /modules/users/server/controllers/users/users.authentication.server.controller.js. This is your main controller for the authentication part of the users module. Now, within this file we can see the signup function is exported:
/* note: there are global variables here, see below */
exports.signup = function (req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
// Init user and add missing fields
var user = new User(req.body);
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
// Then save the user
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
Now, a lot is going on here, but we can break it down.
The req variable is the post request as passed by $http. The res variable is the response the client expects to receive back.
Notice how vm.credentials was passed in $http.post('/api/auth/signup/', vm.credentials)? This is bound to req.body and may be accessed by your server controller from that.
So in this example, the req.body is the required data to create a new user on the server. This is done using mongoose, which has a schema called User. Access this by declaring globals at the top of your controller:
var mongoose = require('mongoose'),
User = mongoose.model('User');
You can see that a new user is instantiated above. It is saved via the mongoose call .save().
Lastly, your server functions should response to the client's request using the res variable passed to the function. See how once the user is created successfully, the function calls
res.jsonp(user);
This is success() to the client, which accepts the response and binds it to a local variable vm.authentication.user
Hope this helps!

Use of AngularJS Factory for Authentication

New to AngularJS.. I want to build a simple Logon screen using a logon page, utilising a controller (I call it 'AccessCtrl') and service.
I want the controller to make use of a service (I called it 'AuthService'), which will perform the REST call that verifies the username/password, and, will also contain information about the success or failure of that logon attempt.
I want to receive information about the last login attempt (as returned in by the REST call). For now - just a string which I want to show on the logon screen, (eg 'password invalid' or 'account expired', or 'welcome'). I'm making this a property of the AuthService service which I hope to display.
My view, has a form with username, password and a submit button that calls the controller's login() method. I'm not including it here for brevity. I don't think thats where the problem lies.
To start with, I want to capture when the server is down/unavailable, etc, and also report this, using the same service. To start with - all calls will fail,(because I have an invalid url).
The controller is defined like this:
angular.module('loginApp')
.controller('AccessCtrl', ['$scope','$http','AuthService',
function ($scope,$http,AuthService,Config) {
this.login =function() {
var user={user:this.username,password:this.password,otherCredentials:this.otherCredentials} ;
AuthService.login(user);
this.message=AuthService.message;
};
}]);
My factory service is defined as follows:
.factory('AuthService', ['$http', function ($http) {
var authService = {};
var apiRootUrl="http://somesite.com/urany";
authService.login = function (credentials) {
authService.message="";
$http.post(apiRootUrl+'/login', credentials)
.then(
function (response) {
// populate OK message
authService.message="Welcome !";
},
function (response) {
// Currently - all calls fail, as the URI is invalid
// I want to trap this.
authService.message = "Server unavailable with response status = " + response.status ;
return authService;
},
function(response) {
// this is the notify callback function.
//
});
};
authService.isAuthenticated = function () {
// rerurn true or false if previously authenticated
return true;
};
return authService;
}])
;
The problem is that my invalid message ('Server unavailable with response status...') does not appear in my view.
In stepping through the code, the correct authService function is called, but, this does not seem to be populated into the controller/view.
I have a feeling this is a timing issue, where the controller that is executing
this.message=AuthService.message;
before the call actually comes back from the post - but I'm not sure that is the case or how to fix that.
any help/clues welcome.
thanks.
S
Have you tried something like this?
Angular Service Code:
//call the service
AuthService.login(user).then(function(response){//begin call back
//store the response data message object property returned from the service
$scope.message = response.message;
}//end call back

Angular service, $http.get() with a route param?

Typically when asking the API endpoint for JSON, I'd write something like this:
factory('User', function($http) {
return {
get: function() {
return $http.get('/api/users');
}
}
});
However, how can I add a route parameter to get a specific user (RESTful show method)?
i.e. /api/users/1 to get user number one. But I want it to be dynamic based on the logged in user.
You can use the $resource factory instead of using $http. As stated in the documentation $resource is:
A factory which creates a resource object that lets you interact with
RESTful server-side data sources.
To do what you want, you can simply declare it like this:
factory('User', function($resource) {
var UserResource = $resource('/api/users/:id');
return UserResource;
});
Usage:
.controller('Ctrl', function($scope, User) {
// Sends GET /api/users/1
User.get({id: '1'}).$promise.then(function(user) {
// expects a single user data object
console.log(user);
});
// Sends GET /api/users
User.query().$promise.then(function(users) {
// expects an array of user data objects
console.log(users);
});
});

How to get logged user with Angular?

Maybe I am missing something very trivial, but I can't find an answer.
I am implementing a webapp based on nodejs, express and angular for the client side.
I handle my signup and sessions through passport.js. Therefore, server-side, I can access the logged user through request.user.
Now, I have a logged user which goes on its profile page, displayed through an angular view.
Here is the issue: In order to show them user information now I am thinking to send an $http request to the server, which takes the user from request and sends it back to the client where it is displayed. However, this sounds weird to me.
So here is my question: Is there any way to access the user in the session thruogh angular? If so, what user information is actually stored in the client?
Thanks in advance, and apologies if this is something too trivial to be asked:/
You will need to create a service in Angular that requests the current user, and stores the result so you can retrieve it for use in your controllers. There is nothing built in to Angular for this; you will have to create it your self. However, it's fairly straight forward.
myapp // assume was previously defined using var myapp = angular.module('myapp', []);
.factory('principal', ['$http', '$q', function($http, $q) {
var _identity = undefined;
return {
// this function returns the current _identity if defined; otherwise, it retrieves it from the HTTP endpoint
identity: function(setIdentity) {
if (setIdentity) {
_identity = setIdentity;
return;
}
var deferred = $q.defer();
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
$http.get('/path/to/endpoint')
.success(function(result) {
_identity = result;
deferred.resolve(_identity);
})
.error(function() {
_identity = undefined;
deferred.reject();
});
return deferred.promise;
}
};
}]);
This principal service has one method at the moment, identity(). This method returns a promise. If the identity has already been retrieved, it will resolve with that value immediately. If not, it will attempt to get it from an HTTP endpoint. If the HTTP call succeeds, it will memoize the result to _identity and resolve the promise. If the call fails, the promise will be rejected. identity has a secondary use. If you supply it with a single parameter, it will set that value as the identity and return nothing. This is useful if you already have the identity and want to set it right away, for example, after they successfully sign-in.
You could manage the sign-in page like this:
myapp.controller('SignInCtrl', ['$scope', 'principal', '$http', function($scope, principal, $http) {
// these two values will be bound to textboxes in the view
$scope.username = '';
$scope.password = '';
// this function will be called when the sign in form is submitted
$scope.submit = function() {
$http.post('/path/to/signin', {username: $scope.username, password: $scope.password })
.success(function(identity) {
// assumes /path/to/signin returns a JSON representation of the signed-in user upon successful authentication
// presumably the endpoint also sets a cookie representing an auth token or something of that nature. the browser will store this automatically for you
principal.identity(identity); // set the identity immediately
// do whatever else on successful login, like redirect to another route
});
}
}]);
And a controller somewhere else that needs the current identity could do something like this:
myapp.controller('MyCtrl', ['$scope', 'principal', function($scope, principal) {
// retrieve the identity. when it resolves, set user on the scope
principal.identity().then(function(identity) {
// after this, you can use user in your view or later in your controller
$scope.user = identity;
});
}]);
Now you have a way of storing the identity immediately after sign-in. I do make an assumption that your code that signs the user in sets a cookie to represent an auth token or whatever in your signin endpoint. The good thing about this is that if the user refreshes their browser, or the cookie is stored for a period of time, the user can just visit your app and the identity will resolve it using that token cookie automatically.
This plunk is a working demo of a more elaborate set up. Some of it may not apply to you (for example, it uses ui-router instead of regular routing), but it should be a reasonable reference point.

Resources