share data between 2 different controller with shared service - json

Hallo i have 2 different controller and i want to share some data from the first to the second.
First Controller:
validationApp.controller('loginCtrl'['auth','resetpass','$scope',function(auth,resetpass,$scope) {
$scope.login = function() {
auth.login($scope);
};
The auth service is:
validationApp.service('auth',function ($http,ipCookie,$rootScope,$state,localStorageService) {
$rootScope.authorized = false;
// function to submit the form after all validation has occurred
this.login = function ($scope) {
var hash1 =CryptoJS.SHA256($scope.password)
var rootElem = {};
var loginRequest = {
username: $scope.username,
hash: hash1.toString(CryptoJS.enc.Hex)
};
rootElem.loginRequest = loginRequest;
var makejson = JSON.stringify(rootElem);
$http({
method: 'PUT',
url: url+'/users/'+ $scope.username +'/login/',
data: makejson,
headers:{'Content-Type':'application/json'}
})
.success(function (data,status){
if (200 == status) {
if((data.loginResponse.roles[0] == "USER") && (data.loginResponse.roles[1] == "ADMIN")){
$rootScope.authorized = true;
$state.go('admin');
}
else {
$rootScope.authorized = true;
$state.go('user');
}
}
})
.error(function(data,status){
if (400 == status) {
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(401 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(500 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
})
}
data is the returned JSON from Backend.
I want to share some JSON data for example data.loginResponse.username in the second controller.
The second controller is:
validationApp.controller('Secondcontroller'['auth','$scope','$state',function(auth,$scope){}]);
It's for make welcome {{username}} after login.

If you want to share the data to another controller you could use $rootScope if you only need the username from the first controller like this:
Your first controller:
validationApp.controller('Firstcontroller', function(.....){
$scope.login = function() {
var data = auth.login($scope);
$rootScope.username = data.loginResponse.username;
};
});
Your second controller:
validationApp.controller('Secondcontroller', function(.....){
You could access $rootScope.username inside here...
});

Related

VueJs Axios Post FormData Parameters

We are using Vue in our frontend application, and for one of our REST service our backend server(using spring and java) expects to have the below data structure:
public class MAProductsUploadRequest
{
public List<MAProductUploadRequest> products;
}
public class MAProductUploadRequest {
public String productName;
public String productDescription;
public double productPrice;
public int productOrder;
public MultipartFile productImage=null;
public double cropX;
public double cropY;
public double cropWidth;
public double cropHeight;
public int categoryId;
}
And in our Vuejs application we tried to post the data as in the below code:
addProducts: function () {
console.log("Add Products Working. Total Product Count:"+this.excelProducts.length);
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
for (let i=0;i<this.excelProducts.length;i++ ) {
console.log("Starting loop:"+i);
var prod = this.excelProducts[i];
console.log("Product Before:"+prod);
if (document.getElementById('photo-image-'+i) !== null) {
if(document.getElementById('photo-image-'+i).files.length !== 0) {
console.log("Getting Image For Prod");
prod.productImage = document.getElementById('photo-image-'+i).files[0] ;
}
}
prod.cropX = this.cropProp.x;
prod.cropY = this.cropProp.y;
prod.cropWidth = this.cropProp.width;
prod.cropHeight = this.cropProp.height;
prod.rotate = this.cropProp.rotate;
console.log("Product After:"+prod);
formData.append("products[]",prod);
}
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
//console.log("Form Data:"+formData.products);
if (formData.products !== null) {
axios.post(`${API_URL}/company/uploadProducts`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.excelProducts = [];
this.isPhotoChosen = false;
this.isPhotosChosen = [];
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
} else {
console.log("Form Data Is Empty");
}
},
But when we use this code (even if the photo-image was null) the backend server returns HTTP 500 error. Because the products array seems null.
I wasn't able to figure it out where the problem may be in the Vuejs code?
EDIT: (I'VE also tried the below code but the still same result)
addProducts: function () {
console.log("Add Products Working. Total Product Count:"+this.excelProducts.length);
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
let prods = [];
for (let i=0;i<this.excelProducts.length;i++ ) {
console.log("Starting loop:"+i);
let prod = this.excelProducts[i];
let subFormData = new FormData();
subFormData.append("productName",prod.productName);
subFormData.append("productDescription",prod.productDescription);
subFormData.append("productPrice",prod.price);
subFormData.append("categoryId",prod.categoryId);
subFormData.append("cropX",this.cropProp.x);
subFormData.append("cropY",this.cropProp.y);
subFormData.append("cropWidth",this.cropProp.width);
subFormData.append("cropHeight",this.cropProp.height);
prods.push(subFormData);
if (document.getElementById('photo-image-'+i) !== null) {
if(document.getElementById('photo-image-'+i).files.length !== 0) {
console.log("Getting Image For Prod");
subFormData.productImage = document.getElementById('photo-image-'+i).files[0] ;
}
}
}
formData.append("products",prods);
console.log("Form Data:"+formData);
if (formData.products !== null) {
axios.post(`${API_URL}/company/uploadProducts`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.excelProducts = [];
this.isPhotoChosen = false;
this.isPhotosChosen = [];
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
//document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
} else {
console.log("Form Data Is Empty");
}
},
What I'm actually trying to achive is, our below code works fine when sending single product info to our backend service, but I want to make it an array so send multiple products at once:
addProduct: function () {
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
formData.append('productName', this.product.name);
formData.append('productDescription', this.product.description === '' ? "" : this.product.description);
formData.append('productPrice', this.product.price);
formData.append('categoryId', this.product.categoryId);
if(document.getElementById('photo-image').files.length !== 0) {
formData.append('productImage', document.getElementById('photo-image').files[0]);
}
formData.append('cropX', this.cropProp.x);
formData.append('cropY', this.cropProp.y);
formData.append('cropWidth', this.cropProp.width);
formData.append('cropHeight', this.cropProp.height);
formData.append('rotate', this.cropProp.rotate);
console.log(formData);
axios.post(`${API_URL}/company/products`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.isPhotoChosen = false;
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
},
Does anyone have any idea about that?
You can also look at the screenshot of my application in below(I want to send all the items in screenshot , at once )
Your issue is probably il the formData.append("products[]",prod) method of your FormData class, try changing formData.append("products[]",prod) with formData.products.push(prod).
Furthermore in your axios call the payload should be formData.products if you API endpoint expects the products right?
Try axios.post(${API_URL}/company/uploadProducts, formData.products, header).
I do not see any syntax issue relative to Vue, hope this helps. (And of course check what is sent by XHR in devtools as suggested in the comments)

Routing is not working in AngularJS

The routing is not working for the index.html. It is even giving a compiler error. Index.html is my startup page. Through Header details link the Add Header.html page should open. I have added the whole code in plunkr ["https://plnkr.co/edit/w9eWiHKvSDrf0viERgoX?p=preview"]
app.js
var MyApp = angular.module('MyApp', ['ngRoute']);
// configure our routes
MyApp.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
.when('/AddHeader', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
// route for the about page
.when('/ProjectIDCreation', {
templateUrl: '/ProjectIDCreation.html',
controller: 'headerCtrl'
})
});
HeaderCtrl.js
var app = angular.module('MyApp');
var baseAddress = 'http://localhost:49754/api/TimeSheet/';
var url = "";
//var app = angular.module('MyApp');
//app.controller('mainController', function ($scope) {
// console.log('mainController');
//});
app.factory('userFactory', function ($http) {
return {
getHeadersList: function () {
url = baseAddress + "FetchHeaderDetails";
return $http.get(url);
},
addHeader: function (user) {
url = baseAddress + "InsertHeaderDetails";
return $http.post(url, user);
},
updateHeader: function (user) {
url = baseAddress + "UpdateHeaderDetails";
return $http.put(url, user);
}
};
});
//var app = angular.module('MyApp');
app.controller('headerCtrl', function PostController($scope, userFactory) {
$scope.users = [];
$scope.user = null;
$scope.editMode = false;
//Fetch all Headers
$scope.getAll = function () {
userFactory.getHeadersList().success(function (data) {
$scope.users = data;
}).error(function (data) {
$scope.error = "An Error has occured while Loading users! " + data.ExceptionMessage;
});
};
//Add Header
$scope.add = function () {
var currentUser = this.user;
userFactory.addHeader(currentUser).success(function (data) {
$scope.addMode = false;
currentUser.HeaderID = data;
$scope.users.push(currentUser);
$scope.user = null;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Adding user! " + data.ExceptionMessage;
});
};
//Edit Header
$scope.edit = function () {
$scope.user = this.user;
$scope.editMode = true;
$('#userModel').modal('show');
};
//Update Header
$scope.update = function () {
var currentUser = this.user;
userFactory.updateHeader(currentUser).success(function (data) {
currentUser.editMode = false;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating user! " + data.ExceptionMessage;
});
};
//Model popup events
$scope.showadd = function () {
$scope.user = null;
$scope.editMode = false;
$('#userModel').modal('show');
};
$scope.showedit = function () {
$('#userModel').modal('show');
};
$scope.cancel = function () {
$scope.user = null;
$('#userModel').modal('hide');
}
// initialize your users data
$scope.getAll();
});
Make sure the file path which you have used in script tags are correct. Which in the plnkr were not correct. Also i found you had two modules defined avoid doing that. Also you are importing angular, jquery, bootstrap more than once dont do that.
Below is the corrected code
Edited plnkr
var app = angular.module('MyApp', ['ngRoute']);
// configure our routes
app.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
.when('/AddHeader', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
// route for the about page
.when('/ProjectIDCreation', {
templateUrl: 'ProjectIDCreation.html',
controller: 'headerCtrl'
})
});
var baseAddress = 'http://localhost:49754/api/TimeSheet/';
var url = "";
app.factory('userFactory', function ($http) {
return {
getHeadersList: function () {
url = baseAddress + "FetchHeaderDetails";
return $http.get(url);
},
addHeader: function (user) {
url = baseAddress + "InsertHeaderDetails";
return $http.post(url, user);
},
updateHeader: function (user) {
url = baseAddress + "UpdateHeaderDetails";
return $http.put(url, user);
}
};
});
//var app = angular.module('MyApp');
app.controller('headerCtrl', function PostController($scope, userFactory) {
$scope.users = [];
$scope.user = null;
$scope.editMode = false;
//Fetch all Headers
$scope.getAll = function () {
userFactory.getHeadersList().success(function (data) {
$scope.users = data;
}).error(function (data) {
$scope.error = "An Error has occured while Loading users! " + data.ExceptionMessage;
});
};
//Add Header
$scope.add = function () {
var currentUser = this.user;
userFactory.addHeader(currentUser).success(function (data) {
$scope.addMode = false;
currentUser.HeaderID = data;
$scope.users.push(currentUser);
$scope.user = null;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Adding user! " + data.ExceptionMessage;
});
};
//Edit Header
$scope.edit = function () {
$scope.user = this.user;
$scope.editMode = true;
$('#userModel').modal('show');
};
//Update Header
$scope.update = function () {
var currentUser = this.user;
userFactory.updateHeader(currentUser).success(function (data) {
currentUser.editMode = false;
$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating user! " + data.ExceptionMessage;
});
};
//Model popup events
$scope.showadd = function () {
$scope.user = null;
$scope.editMode = false;
$('#userModel').modal('show');
};
$scope.showedit = function () {
$('#userModel').modal('show');
};
$scope.cancel = function () {
$scope.user = null;
$('#userModel').modal('hide');
}
// initialize your users data
$scope.getAll();
});
<li></i>AddHeader</li>
<li></i>ProjectIDCreation</li>
(in .html don't forget / )
.config(
[ '$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
.when('/AddHeader', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
.when('/ProjectIDCreation', {
templateUrl: '/ProjectIDCreation.html',
controller: 'headerCtrl'
})
.otherwise('/', {
templateUrl: 'AddHeader.html',
controller: 'headerCtrl'
})
}
]);

Getting the values of a returned JSON object in angular js

I am new to angular and node.js.
Basically, I have a table of items and in each row, there is a button click.
If I click the button which is edit, the details should appear in its corresponding textbox for editing.
router.route('/contacts/getone/:pk')
.get(function(req, res, next){
pg.connect(connectionString, function(err, client, done) {
//var id = {pk:req.body.pk};
var contacts = [];
console.log("get1");
console.log(req.params.pk);
var query = client.query("select * from contacts where pk=($1)", [req.params.pk]);
query.on('row', function(row) {
contacts.push(row);
});
query.on('end', function() {
done();
return res.json(contacts);
});
});
});
And this is my angular controller code.
$scope.editContact = function(id) {
contact.getone(id)
.success(function(data) {
$scope.contactlist = data;
//console.log("geone");
//document.getElementById("fname").value = $scope.contactlist.firstname;
//console.log("getall");
//console.log($scope.contactlist.firstname);
//console.log(data["firstname"]);
$scope.formData.firstname = $scope.contactlist.firstname;
$scope.formData.lastname = $scope.contactlist.lastname;
$scope.formData.address = $scope.contactlist.address;
$scope.formData.contact = $scope.contactlist.contact;
// $scope.loading = false;
});
};
Can anyone tell me how to access the values in data which is returned by my node.js code? The code I have in my angular returns undefined values like $scope.contactlist.firstname is undefined.
This is the image of when I do console.log(data);
#Rayin Dabre
----This is my the code of my controller.
angular.module('ContactsControl', [])
.controller('contactController', ['$scope', '$http', 'contact', function($scope, $http, contact) {
$scope.formData = {};
contact.get()
.success(function(data) {
console.log("getall");
$scope.contactlist = data;
// $scope.loading = false;
});
$scope.editContact = function(id) {
contact.getone(id)
.success(function(data) {
$scope.contactlist = data;
//console.log("geone");
//document.getElementById("fname").value = $scope.contactlist.firstname;
console.log(data);
//console.log($scope.contactlist.firstname);
//console.log(data["firstname"]);
$scope.formData.firstname = $scope.contactlist.firstname;
$scope.formData.lastname = $scope.contactlist.lastname;
$scope.formData.address = $scope.contactlist.address;
$scope.formData.contact = $scope.contactlist.contact;
// $scope.loading = false;
});
};
You have to define formData as object({}) or else $scope.formData will be undefined and you can not set property of undefined
Data being received from the api is not an object but an array. You need to return the data once you get the row
Server side
router.route('/contacts/getone/:pk')
.get(function(req, res, next) {
pg.connect(connectionString, function(err, client, done) {
var query = client.query("select * from contacts where pk=($1)", [req.params.pk]);
query.on('row', function(row) {
return res.json(row);
});
});
});
Client side
var data = {
$$hashKey: "008",
contact_num: 123,
email: "a#gmail.com",
firstname: "boy",
lastname: "kigwa",
pk: 2
};
$scope.formData = {};
$scope.contactlist = data;
$scope.formData.firstname = $scope.contactlist.firstname;
$scope.formData.lastname = $scope.contactlist.lastname;
$scope.formData.address = $scope.contactlist.address;
$scope.formData.contact = $scope.contactlist.contact;
alert(JSON.stringify($scope.formData));

AngularJS Factory Usage

.factory('MY', function($http){
return {
mustafa: function(){
var factory = {};
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
var yarro = $http.get(url).success(function(response){
return response.data);
});
return yarro;
}
}
})
.controller('nbgCtrl', function() {
$scope.mangas = MY.mustafa();
})
I wanna use json data above like. But it isn't working. Could you guys help me?
You can return the promise, and then resolve it in the controller:
.factory('MY', function($http){
return {
mustafa: function() {
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
return $http.get(url);
}
};
})
Finally, you have to inject the service to the controller.
.controller('nbgCtrl', function($scope, MY) {
MY.mustafa().success(function(response) {
$scope.mangas = response.data;
);
});

Json query result not getting set

I am trying to use a Json request to get data from a login screen. But no matter if the login request is valid or not, I am always getting returned to my home screen. I think I am checking the result incorrectly?
Basically, in my Twitter-Bootstrap enabled site, I have a modal popup that takes the user to a login form.
The values are passed via a json query, to my MVC4 controller. A breakpoint shows I am getting good data.
Here's the scrip that sends the data:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result['success'] == 'true') {
alert("true");
window.location = '#Url.Action("Index", "Home")';
} else {
alert("BAD");
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
And here is the controller method:
[HttpPost]
public JsonResult LoginUser(string username, string password, string rememberMe)
{
string success = "false";
string message = "Not set";
if (username == string.Empty || password == string.Empty)
{
success = "false";
message = "Invalid Username/Password";
}
else
{
if (ModelState.IsValid)
{
var us = new UserService();
var reply = us.Authenticate(username, Security.EncryptText(password));
if (reply == 0)
{
success = "false";
message = "Invalid Username/Password";
}
if (reply != 0)
{
var p = us.GetPerson(reply);
FormsAuthentication.SetAuthCookie(p.Id.ToString(CultureInfo.InvariantCulture), rememberMe == "on");
Session["UserDisplay"] = string.Format("{0} {1} - ({2})", p.Firstname, p.Surname, p.Email);
success = "true";
message = "Login Success";
}
}
}
var result = new { Success = success, Message = message };
var r = new JsonResult
{
Data = result
};
return r;
}
However, I always get the 'BAD' alert. Never the 'true'.
Can I check the result the way I am? Am I attempting to do this the right way? Basically, if I get 'BAD', I don't want the screen to refresh. Infact, I will want to show a message saying what ever is in the 'message' parameter.
Edit: I think 'result' is NULL.