How can I access $stateParams from a service in AngularJS? - angular-ui-router

This is my service:
MetronicApp.factory('ItemService', ['$http', '$sessionStorage', '$stateParams', function($http, $sessionStorage, $stateParams) {
return {
save: function(data, success, error) {
return $http.post(baseUrl + '/shops/' + $sessionStorage.currentShop.id + '/menus/' + $stateParams.menuId + '/categories/' + $stateParams.categoryId + '/items', data).success(success).error(error);
},
update: function(data, success, error) {
return $http.put(baseUrl + '/items/' + data.id, data).success(success).error(error);
},
saveTranslation: function(data, success, error) {
return $http.post(baseUrl + '/itemTranslation', data).success(success).error(error);
},
get: function(itemId, success, error) {
return $http.get(baseUrl + '/items/' + itemId).success(success).error(error);
},
getAll: function(categoryId, success, error) {
console.log("Menu id is: " + $stateParams.menuId);
return $http.get(baseUrl + '/shops/' + $sessionStorage.currentShop.id + '/menus/' + $stateParams.menuId + '/categories/' + $stateParams.categoryId + '/items').success(success).error(error);
}
};
}]);
I want to be able to use $stateParams.menuId in getAll method. At that time, url is:
/menus/54/categories/56/items
But $stateParams is null. How can I get them?

One way to solve this problem would be to pass in the stateParams from the controller at the time you are executing service functions. Just make it a parameter on the functions that need this data, and then provide it when executing those functions.
MetronicApp.factory('ItemService', ['$http', '$sessionStorage', function($http, $sessionStorage) {
return {
save: function(data, stateParams, success, error) {
return $http.post(baseUrl + '/shops/' + $sessionStorage.currentShop.id + '/menus/' + stateParams.menuId + '/categories/' + stateParams.categoryId + '/items', data).success(success).error(error);
},
update: function(data, stateParams, success, error) {
return $http.put(baseUrl + '/items/' + data.id, data).success(success).error(error);
},
saveTranslation: function(data, stateParams, success, error) {
return $http.post(baseUrl + '/itemTranslation', data).success(success).error(error);
},
get: function(itemId, stateParams, success, error) {
return $http.get(baseUrl + '/items/' + itemId).success(success).error(error);
},
getAll: function(categoryId, stateParams, success, error) {
console.log("Menu id is: " + stateParams.menuId);
return $http.get(baseUrl + '/shops/' + $sessionStorage.currentShop.id + '/menus/' + stateParams.menuId + '/categories/' + stateParams.categoryId + '/items').success(success).error(error);
}
};
}]);

Related

Not able to generate Signature For AWS Signature Version 4 in Javascript Angular 8

This is my service in angular 8. For Generating the Header for HTTP Method. It gives me the Error for Signature not getting matched with the signature that I have generated.
With
accessKeyId: "AKIA*******UTIZO5UUP",
secretAccessKey: "n5bndDO***************xb3IA0GvmAVTOaDLNDG"
execute(credentials, request) {
let url = new URL(request.url);
let date = new Date();
credentials.host = url.host;
request.route = url.pathname;
let canonical = this.canonicalRequest(credentials, request, date);
console.log("canonical: ", canonical);
let toSign = this.requestToSign(canonical, credentials, date);
console.log("toSign: ", toSign);
let signature = this.signature(toSign, credentials, date);
console.log("signature: ", signature);
return {
"x-amz-date": this.amzLongDate(date),
Authorization:
"AWS4-HMAC-SHA256 Credential=" +
credentials.accessKeyId +
"/" +
this.amzShortDate(date) +
"/" +
credentials.region +
"/execute-api/aws4_request, " +
("SignedHeaders=content-type;host;x-amz-date" +
(credentials.token ? "x-amz-security-token" : "") +
", Signature=" +
signature),
"Content-Type": "application/json",
"x-amz-security-token": credentials.token || undefined
// host: this.credentials.host,
};
}
canonicalRequest(credentials, request, date) {
return (
"\n" +
this.request.method.toUpperCase() +
"\n" +
(request.route.charAt(0) !== "/" ? "/" + request.route : request.route) + //
"\n" +
this.queryParameters(request.query) +
"\ncontent-type:application/json\nhost:" +
credentials.host +
"\n" +
("x-amz-date:" +
this.amzLongDate(date) +
"\n" +
(credentials.token
? "x-amz-security-token:" + credentials.token + "\n"
: "") +
"\n") +
("content-type;host;x-amz-date" +
(credentials.token ? ";x-amz-security-token" : "") +
"\n") +
this.hashString(this.request.body)
);
}
requestToSign(cRequest, credentials, date) {
return (
"\n" +
"AWS4-HMAC-SHA256\n" +
this.amzLongDate(date) +
"\n" +
this.amzShortDate(date) +
"/" +
credentials.region +
"/execute-api/aws4_request\n" +
this.hashString(cRequest)
);
}
signature(toSign, credentials, date) {
return this.hmac(
this.hmac(
this.hmac(
this.hmac(
this.hmac(
"AWS4" + credentials.secretAccessKey,
this.amzShortDate(date)
),
credentials.region
),
"execute-api"
),
"aws4_request"
),
toSign
).toString();
}
queryParameters(queryParameterObj) {
var pieces = [];
if (queryParameterObj) {
Object.keys(queryParameterObj)
.sort()
.forEach(function(k) {
return pieces.push(
k + "=" + encodeURIComponent(queryParameterObj[k])
);
});
}
return pieces.length > 0 ? pieces.join("&") : "";
}
hashString(str) {
return CryptoJS.SHA256(str).toString();
}
hmac(key, value) {
return CryptoJS.HmacSHA256(value, key);
}
amzShortDate(date) {
return this.amzLongDate(date).substr(0, 8);
}
amzLongDate(date) {
return date
.toISOString()
.replace(/[:\-]|\.\d{3}/g, "")
.substr(0, 17);
}
Then This is my Object For the Method to generate them by which I would Call execute method
credentials = {
region: "us-east-1",
accessKeyId: "AKIA*******UTIZO5UUP",
secretAccessKey: "n5bndDO***************xb3IA0GvmAVTOaDLNDG",
host: "",
token: null
};
request = {
url:
"https://jml******xa.execute-api.us-east-1.amazonaws.com/name-of-app/review/v1",
type: "GET",
method: "GET",
dataType: "json",
contentType: "application/json",
data: { foo: "bar" },
route: "",
query: null,
body: null
};
The isuues is I am able to get the correct canonicalRequest and requestToSign but the signature is not getting matched as it says....
{
"message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/name-of-app/review/v1\n\ncontent-type:application/json\nhost:jq******xa.execute-api.us-east-1.amazonaws.com\nx-amz-date:20200227T162638Z\n\ncontent-type;host;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20200227T162638Z\n20200227/us-east-1/execute-api/aws4_request\n9f4671025ee537c0253df73dc1c673d30e22966b3ac544f03df14e3b85f76238'\n"
}

Parse cloud code afterSave gets triggered twice

I have a aftersave on Parse cloud code. I have made changes to the table once but the aftersave hook triggers twice
1st Update (Actual update)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:37.733Z"}}
2nd Update (Shouldn't happen)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:38.038Z"}}
The only difference between the two updates is the updatedAt time. Will aftersave be triggered even if the update time changes?
How can I avoid the second aftersave execution?
Here is my cloud code :
Parse.Cloud.afterSave("Photos", function (request) {
var albumNameA = "";
var publicUser = "";
var albumOwner = "";
var photoUniqueId = "";
var isApproved = "";
albumNameA = request.object.get("albumTitle");
publicUser = request.object.get("addedBy");
photoUniqueId = request.object.id;
isApproved = request.object.get("approved");
if (request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime()) {
var getAlbumOwner = new Parse.Object.extend("Albums");
var q3 = new Parse.Query(getAlbumOwner);
q3.equalTo("title", albumNameA);
q3.first({
success: function (results) {
console.log("Checking for Creator name " + results.get("creatorName"));
albumOwner = results.get("creatorName");
console.log("Uploading a Photo Final " + albumNameA + "-by-" + publicUser + "--ownedby--" + albumOwner);
console.log("Uploading a Photo" + albumNameA + "-by-" + publicUser + "--" + photoUniqueId + "--" + isApproved);
var install = new Parse.Object.extend("Installation");
var q2 = new Parse.Query(install);
q2.equalTo("privacy", privateUserNo);
q2.equalTo("username", albumOwner);
q2.find({
success: function (results) {
if (!isApproved) {
Parse.Push.send({
where: q2, // Set our Installation query
data: {
alert: "New Photo uploaded by " + publicUser + " ,waiting for approval"
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
}
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
} else if (!(request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime())) {
console.log("all case scenarios");
var getAlbumOwner1 = new Parse.Object.extend("Albums");
var q6 = new Parse.Query(getAlbumOwner1);
q6.equalTo("title", albumNameA);
q6.first({
success: function (results) {
albumOwner = results.get("creatorName");
var sendApproval = new Parse.Object.extend("Photos");
var q4 = new Parse.Query(sendApproval);
q4.descending("updatedAt");
q4.first({
success: function (results) {
var objectIDNeeded = results.id;
var isChanged = results.get("approved");
var currentUpdateTime = results.get("updatedTime");
console.log("Your Photo, " + publicUser + " ,has been approved by " + albumOwner);
var install = new Parse.Object.extend("Installation");
var q5 = new Parse.Query(install);
q5.equalTo("privacy", privateUserNo);
q5.equalTo("username", publicUser);
q5.find({
success: function (results) {
Parse.Push.send({
where: q5, // Set our Installation query
data: {
alert: "Your Photo has been approved by " + albumOwner
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
});

how to open a url from the barcode scanner in phonegap build

i'am using the Barcode Scanner for phonegap build, How would i retrieve the QR Codes URL data and display the webpage into a Iframe or div
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
Right i have tried this but its not working, so how would i get the src of a iframe to load result.text url
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
yep so its working :)
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
that works :)

MVC4 #Html.Checkboxfor issue with Ajax call

I was working with MVC CheckBox for.
#Html.CheckBoxFor(m=>m.IsActive, new { #id = "IsActive",#checked = "checked" })
if ($('#frmmenu').valid())
{
//alert("MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val());
alert("MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val());
$.ajax({
type: 'POST',
url: '/api/MenuWebApi/SetMenu',
data: "MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val(),
success: function (data)
{
if (data.Success == true)
{
//window.location = '/Profile/UserProfile';
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
dataType: "json",
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
with passing data when checkbox is checked it is giving true value, but if unchecked then it will give true value not false, how could i do?
please help me anyone.
Regards
Try with this:
var isActive = ($('#IsActive').attr('checked') == 'checked');
// $('#IsActive').attr('checked') will return
// 'checked' or undefined - if not checked/not containing 'checked' attribute

How to make XMLHttpRequest work over HTTPS on google chrome?

I researched about this a lot, but couldn't find the magic.
Actually I want to populate a list of city pin code no. using JQuery autocomplete UI. It's a https page. It's working in Firefox but not in Google Chrome. Can anyone help me to resolve this issue. Thanks in Advance.
In the following is my code:
function zipAutoCompletet(prefix) {
jQuery("#" + prefix + "_zip").autocomplete({
source: function(request, response) {
jQuery.ajax({
url: "http://ws.geonames.org/postalCodeSearchJSON",
dataType: "jsonp",
data: {
style: "full",
maxRows: 12,
postalcode_startsWith: request.term
},
success: function(data) {
response(
jQuery.map(data.postalCodes, function(item) {
return {
label:
item.placeName +
(item.adminCode1
? ", " + item.adminCode1
: "") +
", " +
item.postalCode +
", " +
item.countryCode,
value: item.postalCode
};
})
);
jQuery(".ui-autocomplete").css("width", "188px");
}
});
},
minLength: 2,
select: function(event, ui) {
var myString = new String(ui.item.label);
var address = myString.split(",");
jQuery("#" + prefix + "_city").val(address[0]);
jQuery("#" + prefix + "_city").addClass("activated");
jQuery("#" + prefix + "_city").trigger("change");
jQuery("#" + prefix + "_city")
.parents(".row")
.removeClass("error-row");
jQuery("#" + prefix + "_city")
.parents(".row")
.addClass("ok-row");
var countryCode = address[3] ? address[3] : address[2];
countryCode = jQuery.trim(countryCode);
var countryName = jQuery(
"#" +
prefix +
'_country option[value="' +
jQuery.trim(countryCode) +
'"]'
).text();
jQuery("#countryContainer .jqTransformSelectWrapper span").html(
countryName
);
jQuery("#countryContainer .jqTransformSelectWrapper").addClass(
"selected-jqtranform"
);
jQuery("#" + prefix + "_country")
.parents(".row")
.addClass("ok-row");
jQuery("#" + prefix + "_country")
.parents(".row")
.removeClass("error-row");
jQuery("#" + prefix + "_country").val(jQuery.trim(countryCode));
var stateCode = address[2] ? address[1] : "";
stateCode = jQuery.trim(stateCode);
if (countryCode == "US") {
var base = base_url;
base = base.replace("https", "http");
jQuery.ajax({
url: base + "/getStateName",
dataType: "jsonp",
data: { stateCode: stateCode },
success: function(data) {
stateName = data;
jQuery("#jc_state").val(stateName);
jQuery("#jc_state").addClass("activated");
jQuery("#jc_state")
.parents(".row")
.removeClass("error-row");
jQuery("#jc_state")
.parents(".row")
.addClass("ok-row");
jQuery("#jc_state").trigger("change");
formValidate();
}
});
} else {
stateName = stateCode;
jQuery("#jc_state").val(stateName);
jQuery("#jc_state").addClass("activated");
jQuery("#jc_state")
.parents(".row")
.removeClass("error-row");
jQuery("#jc_state")
.parents(".row")
.addClass("ok-row");
jQuery("#jc_state").trigger("change");
formValidate();
}
jQuery("#" + prefix + "_zip")
.parents(".row")
.addClass("ok-row");
jQuery("#" + prefix + "_zip")
.parents(".row")
.removeClass("error-row");
},
open: function() {
jQuery(this)
.removeClass("ui-corner-all")
.addClass("ui-corner-top");
},
close: function() {
jQuery(this)
.removeClass("ui-corner-top")
.addClass("ui-corner-all");
},
change: function(event, ui) {
if (ui.item === null) {
jQuery("#" + prefix + "_zip")
.parents(".row")
.removeClass("ok-row");
jQuery("#" + prefix + "_zip")
.parents(".row")
.addClass("error-row");
$("#" + prefix + "_zip").val("");
}
}
});
}
If you are on https page, browser will block requests to non-secure resources (http).
Regularly you should see some notification about that. Looks like other browsers does not block non secure AJAX requests on secured pages by default, but google chrome does.
In your code, you have hardcoded URL:
url: "http://ws.geonames.org/postalCodeSearchJSON",
If that is cross domain request and it supports HTTPS, you can change it like this:
url: "//ws.geonames.org/postalCodeSearchJSON",
As you can see, protocol is not specified there. Browser will take page default protocol (http or https) and use it to request data.

Resources