How to call angular service method from controller? - javascript

I'm bit new in angular. I've built 'Employee Search' Service module. Here is the code...
// Service for employee search
app.service('employeeSearchService', function($http, resourceServerAddress){
this.empList = [];
// Method for clearing search employee list
this.clearEmpList = function(){
this.empList = [];
}
// Method for fetching employee search list
this.fetchEmpList = function(){
return this.empList;
}
// Method for making employee search
this.searchEmpList = function(empName){
var postData = {
empName:empName,
};
$http({
method: 'POST',
url: resourceServerAddress,
data : postData
}).then(function successCallback(response) {
console.log('Response Data : '+response);
if(response['data']['status'] === 'success'){
console.log('Response received successfully with status=success');
if(response['data']['data'].length)
{
console.log('matches found for employee search');
this.empList = response;
}
else
{
console.log('no matches found for employee search');
this.empList = [];
}
}
if(response['data']['status'] === 'error'){
console.log('Response received successfully with status=error');
}
}, function errorCallback(response) {
console.log('Error occur at time of processing request');
});
}
});
Then, I'm using following code in my Controller to fetch data from this Service module.
employeeSearchService.searchEmpList(empName);
empSearchResponseList = employeeSearchService.fetchEmpList();
console.log('Search response from server module : '+empSearchResponseList);
I can see from my chrome console that, I'm getting data from my AJAX call with all console message from Service module. But, can't able to catch those data in Controller variable.
I think the way, I'm using 'searchEmpList()' & 'fetchEmpList()' in my controller it's not the right way. But, can't able to find out how to modify that one.
Need Some Guidance -.-
--- Controller Code updated ----
// Controller for application Home route
app.controller("HomeController", function($scope, $state, $location, $ionicHistory, $ionicSideMenuDelegate, $http, resourceServerAddress, employeeSearchService) {
console.log('At home controller');
// Check application session. If it's found not exist redirect user to login page
if(window.localStorage.getItem("access_token") === "undefined" || window.localStorage.getItem("access_token") === null) {
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
console.log('Redirecting user to login page-222');
$state.go("login");
}
$scope.empName = '';
$scope.alertMsgBox = false;
$scope.alertMsgText = '';
$scope.employees = [];
$scope.resourceServerAddress = resourceServerAddress;
var empSearchResponseList=null;
// Method for employee search
$scope.searchEmployee = function(form){
console.log('Employee name entered : '+$scope.empName);
console.log('Employee name character length : '+$scope.empName.length);
if($scope.empName.length >= 3 ){
var postData = {
Emp_Name:$scope.empName,
access_token:window.localStorage.getItem('access_token'),
session_id:window.localStorage.getItem('session_id')
};
$http({
method: 'POST',
url: resourceServerAddress,
data : postData
}).then(function successCallback(response) {
console.log('Response Data : '+response);
if(response['data']['status'] === 'success'){
console.log('Response received successfully with status=success');
if(response['data']['data'].length)
{
console.log('matches found for employee search');
$scope.employees = response['data']['data'];
$scope.alertMsgBox = false;
}
else
{
console.log('no matches found for employee search');
$scope.alertMsgBox = true;
$scope.employees = [];
$scope.alertMsgText = 'No matches found.';
}
}
if(response['data']['status'] === 'error'){
console.log('Response received successfully with status=error');
}
}, function errorCallback(response) {
console.log('Error occur at time of processing request');
});
}
}
// Method for showing employee profile
$scope.showEmpProfile = function(empId){
console.log('HomeCtrl - click on profile image of emp id : '+empId);
// Redirecting to home page
$state.go('app.emp-profile', {empId:empId});
}
});

this also seems confusing for me.
the $http call s done asynchronously so when you call fetch it fetches an empty array.
I would do something like this
this.searchEmpList = function(empName){
var postData = {
empName:empName,
};
return $http({
method: 'POST',
url: resourceServerAddress,
data : postData
}).then(function(response) {
console.log('Response Data : '+response);
if(response['data']['status'] === 'success'){
console.log('Response received successfully with status=success');
if(response['data']['data'].length)
{
console.log('matches found for employee search');
return response['data']['data'];
}
else
{
console.log('no matches found for employee search');
return [];
}
}
if(response['data']['status'] === 'error'){
console.log('Response received successfully with status=error');
}
}, function(response) {
console.log('Error occur at time of processing request');
});
}
and in the controller
employeeSearchService.searchEmpList(empName).then(function(data){
console.log('data is ready', data);
});
Also notice that you have to return the $http in order to use .then() in the controller ( returns a promise).
Fot a great styleguide for angular check

Are you sure that you service works?
I prefer this syntax:
.service('Service', function () {
var Service = {
//methods here
}
return Service;
});
And you don't need hard work with 'this'.

Related

Angularjs login authentication issues

I am new using Angularjs and I'm building a login-page using AngularJS through REST API. I'm facing an issue when I am trying to submit my form. I browsed through so many web-site and links, but I din't got proper answer. Please don't tell me to google it, because I already have so many blue links. If you know anything , please correct me and if you have any working example share it .
AngularJS :
var app = angular.module('logapp',['toastr','ngRoute']);
app.factory('Auth', function($http){
var service = {};
service.login = function(username,password) {
$http.post('http://localhost:3000/loginfo',
{
username : username,
password : password
})
.then(
function successCallback(response){
console.log(response.data);
});
};
service.isAuthenticated = function() {
return {
isAuthenticated : false,
}
};
return service;
});
app.controller('credientials', function($scope,$http,Auth) {
$scope.isAuthenticated = false;
$scope.userCred = {
username: '',
password: ''
}
/*-----Form Submition-----*/
$scope.log = function(userCred){
Auth.login(userCred, function(result) {
console.log(Auth);
if (result === true) {
console.log('success');
} else {
$scope.Error = response.message;
}
});
};
First things first, this part
Auth.login(userCred, function(result) {
is Wrong. Your service.login takes 2 parameters. And they are username and password. It does not take any callback.
Right way to do it is like this
Auth.login(userCred.username, userCred.password)
.then(function(result){
console.log(result);
})
.catch(function(err){
console.error(err);
});
Which goes without saying, you refactor your service.login as follows
service.login = function(username,password) {
return $http.post('http://localhost:3000/loginfo',{
username : username,
password : password
})
}

ngMock complains unexpected request when request is expected

My ng app is working fine, but I am trying to write a ngMock test for my controller; I am basically following along the example on angular's website: https://docs.angularjs.org/api/ngMock/service/$httpBackend
The problem I am running into is that it complains about unexpected request even when request is being expected.
PhantomJS 1.9.8 (Windows 8 0.0.0) NotificationsController should fetch notification list FAILED
Error: Unexpected request: GET Not valid for testsapi/AspNetController/AspNetAction
Expected GET api/AspNetController/AspNetAction
What I do not get is that, on the error line, why is there a "tests" word appended before my service url?
I thought it should be sending to 'api/AspNetController/AspNetAction'
What am I doing wrong here. I can't find any one else running into the same problem as me through google.
Edit: I noticed that, if i remove the sendRequest portion from my controller, and have the unit test log my request object in console, i see the following json.
{
"method":"GET",
"url":"Not valid for testsapi/AspNetController/AspNetAction",
"headers":{
"Content-Type":"application/json"
}
}
here is the controller code
angular.module('MainModule')
.controller('NotificationsController', ['$scope', '$location', '$timeout', 'dataService',
function ($scope, $location, $timeout, dataService) {
//createRequest returns a request object
var fetchNotificationsRequest = dataService.createRequest('GET', 'api/AspNetController/AspNetAction', null);
//sendRequest sends the request object using $http
var fetchNotificationsPromise = dataService.sendRequest(fetchNotificationsRequest);
fetchNotificationsPromise.then(function (data) {
//do something with data.
}, function (error) {
alert("Unable to fetch notifications.");
});
}]
);
Test code
describe('NotificationsController', function () {
beforeEach(module('MainModule'));
beforeEach(module('DataModule')); //for data service
var $httpBackend, $scope, $location, $timeout, dataService;
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
$scope = $injector.get('$rootScope');
$location = $injector.get('$location');
$timeout = $injector.get('$timeout');
dataService = $injector.get('dataService');
var $controller = $injector.get('$controller');
createController = function () {
return $controller('NotificationsController', {
'$scope': $scope,
'$location': $location,
'$timeout': $timeout,
'dataService': dataService,
});
};
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch notification list', function () {
$httpBackend.expectGET('api/AspNetController/AspNetAction'); //this is where things go wrong
var controller = createController();
$httpBackend.flush();
});
});
Data service code
service.createRequest = function(method, service, data) {
var req = {
method: method, //GET or POST
url: someInjectedConstant.baseUrl + service,
headers: {
'Content-Type': 'application/json'
}
}
if (data != null) {
req.data = data;
}
return req;
}
service.sendRequest = function (req) {
return $q(function (resolve, reject) {
$http(req).then(function successCallback(response) {
console.info("Incoming response: " + req.url);
console.info("Status: " + response.status);
console.info(JSON.stringify(response));
if (response.status >= 200 && response.status < 300) {
resolve(response.data);
} else {
reject(response);
}
}, function failCallback(response) {
console.info("Incoming response: " + req.url);
console.info("Error Status: " + response.status);
console.info(JSON.stringify(response));
reject(response);
});
});
}
ANSWER:
since dataService created the finalized webapi url by someInjectedConstant.baseUrl + whatever_relative_url passed in from controller, In the test that I am writting, I will have to inject someInjectedConstant and
$httpBackend.expectGET(someInjectedConstant.baseUrl + relativeUrl)
instead of just doing a $httpBackend.expectGET(relativeUrl)
Clearly Not valid for tests is getting prepended to your url somewhere in your code. It's also not adding the hardcoded domain (see note below). Check through all your code and any other parts of the test pipeline that might be adding this to the url.
A couple of points on your code:
avoid hardcoding domain names in your code (I see you've fixed this in your updated answer)
maybe someInjectedConstant could be more explicitly named
there is no need for you to wrap $http with $q, so service.sendRequest can be:
service.sendRequest = function (req) {
$http(req).then(function (response) { // no need to name the function unless you want to call another function with all success/error code in defined elsewhere
console.info("Incoming response: " + req.url);
console.info("Status: " + response.status);
console.info(JSON.stringify(response));
return response.data; // angular treats only 2xx codes as success
}, function(error) {
console.info("Incoming response: " + req.url);
console.info("Error Status: " + response.status);
console.info(JSON.stringify(response));
});
}

Retrieve customer email from ID contained in webhook in Parse.com

I have an App using Parse.com as a backend and an external site that acts as my payment gateway. Upon receiving the customer/subscription webhook data from Stripe I wish to lookup the users email so I can then run a Cloud Code function and change their user status to 'paid'
My webhook receiver is:
Parse.Cloud.define("update_user", function(request, response) {
var data = request.params["data"]
var customer = data.object.customer;
response.success'Working' + request);
});
And I am able to get an email back from stripe from the customer ID using:
Parse.Cloud.define("pay", function(request, response) {
Stripe.initialize(STRIPE_SECRET_KEY);
console.log(JSON.stringify(request.params));
Stripe.Customers.retrieve(
customerId, {
success:function(results) {
console.log(results["email"]);
// alert(results["email"]);
response.success(results);
},
error:function(error) {
response.error("Error:" +error);
}
}
);
});
I need help turning this into a complete function that is run on receipt of every webhook from Stripe. I am also struggling with options for fallback if this does not work for whatever reason.
EDIT
Taking parts of the first answer and I now have:
Parse.Cloud.define("update_user", function(request, response) {
Stripe.initialize(STRIPE_SECRET_KEY);
var data = request.params["data"]
var customerId = data.object.customer;
get_stripe_customer(customerId, 100).then(function(stripeResponse) {
response.success(stripeResponse);
}, function(error) {
response.error(error);
});
});
function get_stripe_customer (customerId) {
Stripe.initialize(STRIPE_SECRET_KEY);
return Stripe.Customers.retrieve(
customerId, {
success:function(results) {
console.log(results["email"]);
},
error:function(error) {
}
}
);
};
My knowledge is really falling down on the Promise side of things and also the callback (success:, error, request response) etc further reading would be appreciated.
This is now working
Out of interest I did this:
Parse.Cloud.define("update_user", function(request, response) {
var data = request.params["data"]
var customerId = data.object.customer;
get_stripe_customer(customerId, 100).then(function(stripeResponse) {
return set_user_status(username, stripeResponse);
}).then(function(username) {
response.success(username);
}, function(error) {
response.error(error);
});
});
function get_stripe_customer (customerId) {
Stripe.initialize(STRIPE_SECRET_KEY);
return Stripe.Customers.retrieve(
customerId, {
success:function(results) {
// console.log(results["email"]);
},
error:function(error) {
}
}
);
};
function set_user_status(stripeResponse) {
Parse.Cloud.useMasterKey();
var emailquery = new Parse.Query(Parse.User);
emailquery.equalTo("username", stripeResponse['email']); // find all the women
return emailquery.first({
success: function(results) {
alert('running set_user_status success');
var user = results;
user.set("tier", "paid");
user.save();
},
error:function(error) {
console.log('error finding user');
}
});
};
open to improvements...
EDIT - I (#danh) cleaned it up a bit. A few notes:
used promises throughout. much easier to read and handle errors
get_stripe_customer requires only one param (that 100 was my idea to charge $100)
set_user_status appears to need only user email as param, which apparently is in the stripeResponse
set_user_status returns a promise to save the user. that will be fulfilled with the user object, not the username
be sure you're clear on how to identify the user. stripe apparently provides email address, but in your user query (in set_user_status) you compare email to "username". some systems set username == email. make sure yours does or change that query.
Parse.Cloud.define("update_user", function(request, response) {
var data = request.params["data"]
var customerId = data.object.customer;
get_stripe_customer(customerId).then(function(stripeResponse) {
var email = stripeResponse.email;
return set_user_status(email);
}).then(function(user) {
response.success(user);
}, function(error) {
response.error(error);
});
});
function get_stripe_customer(customerId) {
Stripe.initialize(STRIPE_SECRET_KEY);
return Stripe.Customers.retrieve(customerId).then(function(results) {
// console.log(results["email"]);
return results;
});
};
function set_user_status(email) {
Parse.Cloud.useMasterKey();
var emailquery = new Parse.Query(Parse.User);
emailquery.equalTo("username", email); // find all the women
return emailquery.first().then(function(user) {
user.set("tier", "paid");
return user.save();
}, function(error) {
console.log('error finding user ' + error.message);
return error;
});
}
Did a quick skim of the docs pertaining to stripe, and it looks like the steps are: (1) make a stripe REST-api call from your client side to get a token, (2) pass that token to a cloud function, (3) call stripe from the parse cloud to finish paying. I understand that you'd like to include a (4) fourth step wherein the transaction is recorded in the data for the paying user.
From the client (assuming a JS client):
var token = // we've retrieved this from Stripe's REST api
Parse.Cloud.run("pay", { stripeToken: token }).then(function(result) {
// success
}, function(error) {
// error
});
On the server:
Parse.Cloud.define("pay", function(request, response) {
var user = request.user;
var stripeToken = request.params.stripeToken;
payStripeWithToken(stripeToken, 100).then(function(stripeResponse) {
return updateUserWithStripeResult(user, stripeResponse);
}).then(function(user) {
response.success(user);
}, function(error) {
response.error(error);
});
});
Now we need only to build promise-returning functions called payStripeWithToken and updateUserWithStripeResult.
// return a promise to pay stripe per their api
function payStripeWithToken(stripeToken, dollarAmt) {
Stripe.initialize(STRIPE_SECRET_KEY); // didn't see this in the docs, borrowed from your code
return Stripe.Charges.create({
amount: dollarAmt * 10, // expressed in cents
currency: "usd",
card: stripeToken //the token id should be sent from the client
});
// caller does the success/error handling
}
// return a promise to update user with stripeResponse
function updateUserWithStripeResult(user, stripeResponse) {
var transactionId = // dig this out of the stripeResponse if you need it
user.set("paid", true);
user.set("transactionId", transactionId);
return user.save();
}

How can i get data from service in angular

I have LoginController and securityService.
This is LoginCtrl
// place the message if something goes wrong
$scope.authMsg = '';
$scope.login = function () {
$scope.authMsg = '';
var loginData = {email: $scope.account.email, password: $scope.account.password};
securityService.login(loginData);
};
This is securityService
login: function (logData) {
var _vm = this;
$http
.post('/api-token-auth/', logData)
.then(function (response) {
// assumes if ok, response is an object with some data, if not, a string with error
// customize according to your api
if (!response.data.token) {
_vm.authMsg = 'Incorrect credentials.';
} else {
$cookieStore.put('djangotoken', response.data.token);
$http.defaults.headers.common.Authorization = 'JWT ' + response.data.token;
$http.get('/api/account/restricted/').then(function (response) {
authService.loginConfirmed();
_vm.currentUser = response.data;
$rootScope.currentUser = response.data;
});
}
}, function (x) {
_vm.authMsg = 'Server Request Error';
});
},
This login is working fine but my problem is i don't know how can get the authMesg from service to controller because that is async. Everytime i get blank message in case of invalid login
you need to use promise service of angular to make you controller and service syn
login: function (logData) {
var _vm = this,d= $$q.defer();
$http
.post('/api-token-auth/', logData)
.then(function (response) {
// assumes if ok, response is an object with some data, if not, a string with error
// customize according to your api
if (!response.data.token) {
_vm.authMsg = 'Incorrect credentials.';
} else {
$cookieStore.put('djangotoken', response.data.token);
$http.defaults.headers.common.Authorization = 'JWT ' + response.data.token;
$http.get('/api/account/restricted/').then(function (response) {
authService.loginConfirmed();
_vm.currentUser = response.data;
$rootScope.currentUser = response.data;
});
}
d.resolve(vm.authMsg);
}, function (x) {
_vm.authMsg = 'Server Request Error';
d.reject(vm.authMsg);
});
},
In controller you need to resolve this promise
securityService.login(loginData).then(function(data){
consol.log(data); // get success data
},function(error){
consol.log(data); // get error message data
})
and inject $q in your service.
This will give you authMsg
securityService.login(loginData).authMsg
But follow #Vigneswaran Marimuthu comments, that is best practice.

Get return value when using call() with node.js

I am currently programming a socket server in node.js using the json-socket module, and am having some trouble.
Currently when a client connects to the server they send a command in a json object with some data for instance a login would look like this
{ type : 'login', data : { username: 'Spero78' } }
to deal with these requests i have a commands object
var commands = {
'login' : authUser,
'register' : userRegister
}
and these functions are called by server.on
server.on('connection', function(socket) {
console.log('Client Connected');
socket = new JsonSocket(socket);
socket.on('message', function(message) {
if(message.type != undefined) {
if(commands[message.type]){
var response = commands[message.type].call(this, message.data);
if(response != undefined){
console.log(response);
socket.sendMessage(response);
} else {
console.log("No Response!");
}
} else {
console.log('Unexpected Command!');
}
}
});
});
The functions return javascript objects but the response var is always undefined and the "No Response!" message is always printed
Here is the authUser function
function authUser(data){
console.log('Auth: ' + data.username);
database.query('SELECT * FROM players WHERE username = ?', [data.username], function(err, results) {
if(results.length < 1){
console.log('Bad Login!');
var response = {
type : 'badlogin',
data : {
//...
}
}
return response;
}
var player = results[0];
var response = {
type : 'player',
data : {
//...
}
}
return response;
});
}
Is there a better way of doing this? or am i missing something that is causing the objects to not return
database.query() is asynchronous, so when you call this function, nodejs don't wait the response of the callback to go to next instruction.
So the value tested on your condition is not the return in the callback, but of the whole authUser function, that's why it's always undefined.
You probably need tor refactor your code.

Categories