Router Navigate Angular 8 hide URL Arguments - javascript

As i have created a method to call to edit page the code is shown below.
SelectStaff(_StaffEmit:any){
let StaffJson = JSON.stringify(_StaffEmit);
let _navigationExtras: NavigationExtras = {
queryParams: {
StaffJson
}
};
this._router.navigate(["StaffInfo"], _navigationExtras);
}
Now, this code redirects to StaffInfo.ts page which is successfully done. Here is the code where i receive my JSON data.
this._routeEdit.queryParams.subscribe(params => {
let StaffParsed = JSON.parse(params.StaffJson);
this.StaffModel.Id = StaffParsed.id;
this.StaffModel.FirstName = StaffParsed.firstName;
this.StaffModel.LastName = StaffParsed.lastName;
this.StaffModel.UserName = StaffParsed.username;
this.StaffModel.Email = StaffParsed.email;
this.StaffModel.Title = StaffParsed.title;
this.StaffModel.CellPhoneNo = StaffParsed.cellPhoneNo;
});
Now i have a problem as i call this JSON data it appends on the URL which i don't want to.
Here is the image below for it.
As i can see it uses GET verb but i don't want to show the data, any POST verb or NON-POST verb method to redirect with data would be appreciated.

The only way is to use skipLocationChange property could be used to protect a user from seeing URL change.

you could encode it in Base64, put in the query param and decode it again whenever you need
//encode to base64
btoa(JSON.stringify({username:"admin",firstname:"John",lastname:"Doe"}))
//eyJ1c2VybmFtZSI6ImFkbWluIiwiZmlyc3RuYW1lIjoiSm9obiIsImxhc3RuYW1lIjoiRG9lIn0
now put this string to the URL and whenever you need it just decode it
//decode to base64
JSON.parse(atob("eyJ1c2VybmFtZSI6ImFkbWluIiwiZmlyc3RuYW1lIjoiSm9obiIsImxhc3RuYW1lIjoiRG9lIn0"))
//"{"username":"admin","firstname":"John","lastname":"Doe"}"

Angular 7.2.0 and above. You can pass state in NavigationExtras object.
It can pass the state without reflecting state in url.
You can access data inside state that is pass by router in routed component and can be accessed inside constructor.
let StaffJson = JSON.stringify(_StaffEmit);
let _navigationExtras: NavigationExtras = {
state: {
StaffJson
}
};
this._router.navigate(["StaffInfo"], _navigationExtras);
}
XYZ Component to which router.navigate(['./XYZ`], _navigationExtras)
constructor(private router: Router) {
this.name = this.router.getCurrentNavigation().extras.state;
let StaffParsed = JSON.parse(params.StaffJson);
this.StaffModel.Id = StaffParsed.id;
this.StaffModel.FirstName = StaffParsed.firstName;
this.StaffModel.LastName = StaffParsed.lastName;
this.StaffModel.UserName = StaffParsed.username;
this.StaffModel.Email = StaffParsed.email;
this.StaffModel.Title = StaffParsed.title;
this.StaffModel.CellPhoneNo = StaffParsed.cellPhoneNo;
}

Related

How to connect loop data to pdfgeneratorapi with wix corvid?

I'm generating PDF by using https://pdfgeneratorapi.com/.
Now I can show data one by one using this code.Can any one give me suggestion how can show all data with loop or any other way?
This below photos showing my template from pdfgenerator .
This is the code I'm using to generate PDF
let communicationWay1=[
{0:"dim"},
{1:"kal"}
];
let cstomerExpence1=[
{0:"dim"},
{1:"kal"}
];
let title="test";
let names="test";
let phone="test";
let email="test";
let maritalStatus="test";
let city="test";
let other="test";
const result = await wixData.query(collection)
.eq('main_user_email', $w('#mainE').text)
.find()
.then( (results) => {
if (results.totalCount>0) {
count=1;
// title=results.items[1].title;
names=results.items[0].names;
email=results.items[0].emial;
phone=results.items[0].phone;
maritalStatus=results.items[0].maritalStatus;
city=results.items[0].city;
other=results.items[0].cousterExpenses_other;
title=results.items[0].title;
communicationWay=results.items[0].communicationWay;
cstomerExpence=results.items[0].cstomerExpence;
}
if (results.totalCount>1) {
names1=results.items[1].names;
email1=results.items[1].emial;
phone1=results.items[1].phone;
maritalStatus1=results.items[1].maritalStatus;
city1=results.items[1].city;
other1=results.items[1].cousterExpenses_other;
title1=results.items[1].title;
communicationWay1=results.items[1].communicationWay;
cstomerExpence1=results.items[1].cstomerExpence;
}
} )
.catch( (err) => {
console.log(err);
} );
// Add your code for this event here:
const pdfUrl = await getPdfUrl
({title,names,email,phone,city,maritalStatus,other,communicationWay,cstomerExpence,title1,
names1,email1,phone1,city1,maritalStatus1,other1,communicationWay1,cstomerExpence1
});
if (count===0) { $w("#text21").show();}
else{ $w("#downloadButton").link=wixLocation.to(pdfUrl);}
BELOW CODE IS BACKEND CODE/JSW CODE.
Also I want to open pdf in new tab. I know "_blank" method can be used to open a new tab.But I'm not sure how to add it with the url
import PDFGeneratorAPI from 'pdf-generator-api'
const apiKey = 'MYKEY';
const apiSecret = 'MYAPISECRET';
const baseUrl = 'https://us1.pdfgeneratorapi.com/api/v3/';
const workspace = "HELLO#gmail.com";
const templateID = "MYTEMPLATEID";
let Client = new PDFGeneratorAPI(apiKey, apiSecret)
Client.setBaseUrl(baseUrl)
Client.setWorkspace(workspace)
export async function getPdfUrl(data) {
const {response} = await Client.output(templateID, data, undefined, undefined, {output: 'url'})
return response
}
Just put it in a while loop with a boolean condition.
You can create a variable, for example allShowed, and set its value to False. After that, create another variable, for example numberOfDataToShow, and set it as the number of elements you want to display. Then create a counter, countShowed, initialized with 0 as its value.
Now create a while loop: while allShowed value is False, you loop (and add data).
Everytime a piece of your data is showed, you increment the value of countShowed (and set it to go on adding/showing data). When countShowed will have the exact same value of numberOfDataToShow, set allShowed to True. The loop will interrupt and all your data will be showed.
You would need to use the Container or Table component in PDF Generator API to iterate over a list of items. As #JustCallMeA said you need to send an array of items. PDF Generator API now has an official Wix Velo (previously Corvid) tutorial with a demo page: https://support.pdfgeneratorapi.com/en/article/how-to-integrate-with-wix-velo-13s8135

How to pass props through window.href react

I have passed props through to different components and pages before but this has been through link or just added these to the component tag itself.
The issue I have here is that the redirect is not going through a link tag or in a component tag and instead I am simply using window.locatio.href ="whatever the url is".
I simply want to pass a variable through to this (I am technically doing a refresh in this situation so window.location.reload() could also work if it is possible).
How would I pass through a variable within this.
When using express you can do fetch statements with an endpoint simialr to (might not be exact syntax) "./page${variableYouWant}" Then access sit in the express file using req.params.variableYouWant.
Is this possible to pass a variable this way and how would I then access it.
Here is the most important snippet of my code.
pageRelocator(mssg) {
if (mssg.length < 35) {
toast.info(`${mssg}`, {
draggable: true,
autoClose: 1500
});
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
toast.error(`${mssg}`, {
draggable: true,
autoClose: 1500
});
//Here I would like to pass a variable
window.location.href = "http://localhost:3000/user-questions";
}
}
EDIT--
componentDidMount() {
const search = this.props.location.mssg;
alert(search); // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get("mssg");
this.setState({
questions: this.getItems(),
WorkStations: this.getWorkStations()
});
}
pageRelocator(mssg) {
if (mssg.length < 35) {
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
window.location.href = `http://localhost:3000/user-questions?mssg=${mssg}`;
}
}
Try using the URLSearchParams which defines utility methods to work with the query string of URL.so to attach a variable you would do
var id=5;
window.location.href = `http://localhost:3000/user-questions?id=${id}`;
and to retreive id from the URL you would do
const search = props.location.search; // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get('id');
Hope this helps
If you want the data to be present even after refresh, try to pass the variable in params.
http://localhost:3000/completed-assessment?your_variable=value
If you want to use this params value you can use
window.location.search
Using URLSearchParams you can get the each params you've sent with the URL.
Please refer https://www.sitepoint.com/get-url-parameters-with-javascript/ for more info

Passing params throught pages with ui-router and angularjs

I would like to pass an object to a controllerA to another controllerB and display that object. To do it, I'm using ui-router with angularjs.
This is my controllerA which build the URL using $state.href():
const url = $state.href('home.stateA', {
objectA: objectA
});
window.open(url, '_blank');
Now, this my route file:
.state('home.stateA', {
url: '/stateA',
template: '<template-b></template-b>',
params: {
// object: null
objectA: null
}
})
And finnaly, I try to get my object in my controllerB like that:
// $scope.object = $stateParams.object;
$scope.object = $stateParams.objectA;
When I console.log $scope.object, I'm getting null which is the default value in my route file.
So what's going wrong ? I'm wondering if $window.open would not be the problem.
Thanks for helping me.
window.open(url, '_blank');
You are opening a new window and trying to pass an object.
Passing a String/Number
You can pass a string/number say id, as part of the URL, if your state URL is defined like '/stateUrl/:id'
and then you can access this using $stateParams.id
Sharing an object
You can use localStorage along with JSON.stringify and JSON.parse to share the object.
Set data
localStorage.setItem('object', JSON.stringify(object));
Get data
var object = JSON.parse(localStorage.getItem('object'));
I have just found the solution ->
ControllerA
const url = $state.href('stateA');
let newTab = $window.open(url);
newTab.objectA = objectA;
ControllerB:
$scope.objectA = $window.objectA
And the state is very simple :
.state('home.stateA', {
url: '/stateA',
template: '<template-b></template-b>',
})
I don't know if it's the best way to implement what I needed but at least it works. it may help someone else.
Thanks guys and have a nice day !
I suggest you use url parameter.
.state('home.stateA', {
url: '/stateA?object',
template: '<template-b></template-b>',
params: {
object: null
}
})
Do when open new tab page
const url = $state.href('home.stateA', {
objectA: JSON.stringify(objectA)
});
In controllerB
$scope.object = JSON.parse($stateParams.objectA);
Because when you are open new tab. The state param is lost

Firebase Function postId error. Javascript

I am using firebase functions and have successfully run a sanitize function.
The problem I am having is my firebase database looks like this.
The ABC123 and the 0l692lPD6EfqUZ4Y4xiCOVmnNmC2 are both sets automatically when a post is created so I would not know what they will be.
I can hard code the first ABC123 and set {postID} for the second one and it runs successfully. But if I set both to posteId it fails.
below is my code. I need to be able to change the ABC123 to postId because I will not know what it will be in my index.js code.
exports.sanitizePost = functions.database
.ref('/posts/ABC123/question/{postId}')
.onWrite(event => {
const post = event.data.val()
if (post.sanitized) {
return
}
console.log("Sanitizing new post " + event.params.pushId)
console.log(post)
post.sanitized = true
post.question = sanitize(post.question)
const promise = event.data.ref.set(post)
return promise
})
function sanitize(s) {
var sanitizedText = s
sanitizedText = sanitizedText.replace(/\bstupid\b/ig, "wonderful")
return sanitizedText
}
I need .ref('/posts/ABC123/question/{postId}') to be .ref('/posts/{postID}/question/{postId}') or somthing that works.
You cannot have the same parameter twice in a path. But you can have two parameters of different names, e.g.
exports.sanitizePost = functions.database
.ref('/posts/{questionId}/question/{postId}')

Web API post parameter

I currently have an issue with a webapi call. I want to download and open a logfile with my ApiController.
I use a javascript function to post a filename to my controller.
Here is a helper function to post the parameter (answer from dystroy):
How to replace window.open(...) with a POST
Now when I use a simple string as parameter in my controller I can’t get the parameter, it is always null.
public HttpResponseMessage PostDownloadLogFile([FromBody]string psFileName)
{
//psFileName is always null
But if I use HttpReqeustMessage as parameter and read the form data from my request it is no problem and it works.
public HttpResponseMessage PostDownloadLogFile(HttpRequestMessage poRequest)
{
var loFormData = poRequest.Content.ReadAsFormDataAsync().Result;
string psFileName = loFormData["psFileName"]; //psFileName is set correct
Is there a solution to get the parameter with a simple parameter in my controller?
Update
This is my javascript helper function:
var loOpenWindow = function (psMethode, psUrl, poData, psTarget) {
var loForm = document.createElement("form");
loForm.action = psUrl;
loForm.method = psMethode;
loForm.target = psTarget || "_self";
if (poData) {
for (var lsKey in poData) {
var loInput = document.createElement("textarea");
loInput.name = lsKey;
loInput.value = typeof poData[lsKey] === "object" ? JSON.stringify(poData[lsKey]) : poData[lsKey];
loForm.appendChild(loInput);
}
}
loForm.style.display = "none";
document.body.appendChild(loForm);
loForm.submit();
};
Call it:
helper.openWindow("POST", apiRoutes.URLS.ApiPostDownloadLogFile, { "psFilename": $scope.data.showLogEntry.FullName });
There should be no problem from the client side code, because the controller methode with HttpReqeustMessage works without problems.
Here is the browser request:
Probably the problem is in your client code sending the data.
[FromBody] parameters must be encoded as =value
then, this does not work:
// Value will be null.
$.post('api/values', value);
// Value will be null.
$.post('api/values', { key: value });
But this work:
$.post('api/values', "=" + value);
Try to change your client code to send just =/path/to/your/file in the body.
Reference: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
Ok I found a solution.
If I use a class as parameter and a property with the given name, it seems to work.
public class Param
{
public string psFileName { get; set; }
}
And
public HttpResponseMessage PostDownloadLogFile(Param poParam)
{
string psFileName = poParam.psFileName; //psFileName is set correct
This is not really a simple parameter but I can live with this solution.

Categories