Pass values to route - aurelia

I have a list of items. When the user clicks on an item, the user will be taken to item details page.
I want to pass an object containing item details(like item's image URL) to the route. However, I don't want to expose it in the routes url.
If there were a way to do something like <a route-href="route: details; settings.bind({url: item.url})">${item.name}</a> that would be gold.
I have seen properties can be passed to a route if defined in the route configuration. However, I don't know how to change that from the template. Another way could be is to define a singleton and store the values there and inject the object to the destination route.
Is there a way to pass values to routes from view (like angular ui-routers param object)?

Okay so I figured out a way to achieve something closer to what I wanted:
Objective: Pass data to route without exposing them in the location bar.
Let's say, we have a list of users and we want to pass the username to the user's profile page without defining it as a query parameter.
In the view-model, first inject Router and then add data to the destination router:
goToUser(username) {
let userprofile = this.router.routes.find(x => x.name === 'userprofile');
userprofile.name = username;
this.router.navigateToRoute('userprofile');
}
Now when the route changes to userprofile, you can access the route settings as the second parameter of activate method:
activate(params, routeData) {
console.log(routeData.name); //user name
}

For those #Sayem's answer didn't worked, you can put any additional data (even objects) into setting property like this:
let editEmployeeRoute = this.router.routes.find(x => x.name === 'employees/edit');
editEmployeeRoute.settings.editObject = employeeToEdit;
this.router.navigateToRoute('employees/edit', {id: employeeToEdit.id});
So editObject will be delivered on the other side:
activate(params, routeConfig, navigationInstruction) {
console.log(params, routeConfig, navigationInstruction);
this.editId = params.id;
this.editObject = routeConfig.settings.editObject;
}
hopes this helps others encountering same problem as me. TG.

Related

Is it possible to change url using vue-router without going to the page?

There is a shop on nuxtjs and on the /catalog page I need to make a "Load more" button. By clicking on it, products should be loaded and the url should be changed to /catalog/page_2 (?page=2 is not suitable).
If I change the url through $router.push nuxt goes to this page, but I need to change the url, but not go anywhere.
Is it possible to somehow undo the reloading but save the changes in the url?
history.pushState copes with the task, but in this case nuxt does not know that the url has changed and when clicking forward / backward in the browser nuxt does not load the goods needed for this page
Paginations logically belong to the main page so It's good to consider them in URL queries, like ?page=2.
also you can use router.replace to change queries.
this.$router.replace({
query: { ...this.$route.query, page: this.page},
})
Do it with this example
https://codesandbox.io/s/withered-darkness-9ezn9?file=/pages/index/_id.vue
Now I can change the filters, categories, and the url changes, but the page does not reload
As you don't want to change the page if you are already on the correct one, check for differences in current page URL first;
const your_query = '?page=2' // containing url params
const currPath = this.$route.fullPath; // containing current path + query params, e.g. '/catalog/?page=2'
const nextPath = `${this.$route.path}?${your_query)}`;
if (currPath !== nextPath) {
//"Abuse" router to change the current's windows url
this.$router.replace(nextPath, undefined, () => {
//If route navigation fails, e.g. due to a same-route navigation or wrong permissions in navigation-guards, handle here
return;
});
}
Alternative would be to directly pass the new query params to the router, as:
this.$router.replace({ query:
page: 2
})

NUXT pass object data into pages with path

I'm really new to Vue and Nuxt so I apologise if this is a simple question.
I'm generating my routes dynamically on making an API call for my data on Index.vue. One API call is enough for me to retrieve all the data i need which is stored in deals_array, so I don't need another API call on my individual page, I just need the data from each deal in deals_array.
<ul>
<li v-for="deal of deals_array" :key="deal.id">
<nuxt-link :to="getSlug(deal)">{{ deal.name }}, {{deal.value}}</nuxt-link>
</li>
</ul>
I'm wondering how do I pass the entire deal object into my pages, so that when I click on the individual nuxt-link I would be able to access that deal object and all its attributes (for each page).
I've taken a look at passing params into nuxt-link but I understand that it only pairs with name attribute and not the path, where I need the path URL in this case.
I may be doing this entirely wrong so I'm hoping to be pointed in the right direction.
Edit - getSlug function
getSlug(deal) {
let name = deal.name;
let dealDetails = deal.details;
let name_hyphen = name.replace(/\s+/g, "-");
let deal_hyphen = dealDetails.replace(/\s+/g, "-");
let nameDealSlug = name_hyphen + "-" + deal_hyphen;
// remove selected special characters from slug
let clean_nameDealSlug = nameDealSlug.replace(
/[&\/\\#,+()$~%.'":*?<>{}]/g,
""
);
let finalSlug = `deals/${clean_nameDealSlug}`;
return finalSlug;
}
I'm assuming you have gone through this: https://router.vuejs.org/api/.
You can just pass the entire object:
<nuxt-link :to="{ path: 'test', query: {a: 1, b: 2}}">Test Page</nuxt-link>
And your URL will become something like this:
http://localhost:3000/test?a=1&b=2
The entire object can be simply passed.
This will be available to your next page in $route object in the url query.
Otherwise if you don't want to get your deal object exposed just use the concepts of vuex. Store the entire deal object in the vuex and pass ids to different pages. And from pages retrieve the deal object through vuex.

How to create standalone custome page?

I'm looking for a way to create single page model/ standalone single page.
It's like a custom single page for 'About Us', 'Home Page','Our Team',etc.
They are single page with backend options.
Anyone have any idea ?
So you need to create all needed type of files, like route JS file, template file, add info about that file into routes/index.js
example:
create file routes/views/aboutUs.js :
var keystone = require("keystone");
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res);
var locals = res.locals;
// locals.section is used to set the currently selected
// item in the header navigation.
locals.section = "about-us";
locals.title = "About our company";
// Render the view
view.render("aboutUs");
};
create template file templates/aboutUs.pug :
block content
p Our company is super cool. We based it here long time ago
Put all your static content into template with correct syntax and css
Finally make addition to routes/index.js file:
app.get("/aboutUs", routes.views.aboutUs);
if you need to control user access to page also add such string
app.all("/aboutUs*", middleware.requireUser);
And dont forget to restart the app to see changes
That's clearly not what OP is asking for. They're asking if there is a way to create a single ADMIN UI editable page for Home, About Us, and so on. My answer is that I don't believe that is possible with KeystoneJS. Which is annoying, because I have clients that want that and Keystone would be perfect otherwise. Seems the only way to do it is create a list, auto create a record if one doesn't exist, and set "nocreat", and "novelette" on the list.

How to reuse data between routes in Aurelia?

I have an user entity in the system and the following route fetches it from server and displays its details:
routerConfiguration.map([
// ...
{route: 'user/:id', name: 'user-details', moduleId: './user-details'}
]);
Now I want to display an edit form for the displayed user. I have the following requirements:
Edit form should have a separate URL address, so it can be sent to others easily.
When user clicks the Edit button on the user's details page, the edit form should use an already loaded instance of the user (i.e. it should not contact the API again for user details).
When user clicks the Edit button on the user's details page and then the Back button in the browser, he should see the details page without edit form again.
1st attempt
I tried to define the edit form as a separate page:
routerConfiguration.map([
// ...
{route: 'user/:id/edit', name: 'user-edit', moduleId: './user-edit'}
]);
This passes the #1 and #3 requirement but it has to load the user again when the edit form is opened.
I don't know any way to smuggle some custom data between the routes. It would be perfect if I could pass the preloaded user instance to the edit route and the edit component would use it or load a new one if it is not given (e.g. user accesses the URL directly). I have only found how to pass strings to the routes in a slighlty hacky way.
2nd attempt
I decided to display the edit form in a modal and show it automatically when there is a ?action=edit GET parameter. The code inspired by this and this question:
export class UserDetails {
// constructor
activate(params, routeConfig) {
this.user = /* fetch user */;
this.editModalVisible = params.action == 'edit';
}
}
and when the user clicks the Edit button, the following code is executed:
displayEditForm() {
this.router.navigateToRoute('user/details', {id: this.user.id, action: 'edit'});
this.editModalVisible = true;
}
This passes #1 (the edit url is user/123?action=edit) and #2 (the user instance is loaded only once). However, when user clicks the Back browser button, the URL changes as desired from user/123?action=edit to user/123 but I have no idea how to detect it and hide the edit form (the activate method is not called again). Therefore, this solution fails the #3 requirement.
EDIT:
In fact, I have found that I can detect the URL change and hide the edit form with event aggregator:
ea.subscribe("router:navigation:success",
(event) => this.editModalVisible = event.instruction.queryParams.action == 'edit');
But still, I want to know if there is a better way to achieve this.
The question is
How to cope with this situation in a clean and intuitive way?
How about adding a User class that will serve as the model and use dependency injection to use it in your view-models?
export class User {
currentUserId = 0;
userData = null;
retrieve(userId) {
if (userId !== this.currentUserId) {
retrieve the user data from the server;
place it into this.userData;
}
return this.userData;
}
}

Dynamically Adding / Removing Route in Durandal Router when application is loaded

I need help in dynamically adding/removing route in Durandal Router. What I want is after user is logged in then I would be able to add or remove specific route depending upon logged in user's type.
I tried to add/remove route from visibleRoutes/allRoutes array ... but get binding exception from knockout library...
I was hoping it would be common scenario... but still couldn't find any solution ... please help me in fixing this issue.
Thanks.
Wasim
POST COMMENTS:
I tried this function to dynamically hide/show route... and similary tried to add/remove route from allRoutes[] ... but then get exception on knockout bidning
showHideRoute: function (url,show) {
var routeFounded = false;
var theRoute = null;
$(allRoutes()).each(function (route) {
if (url === this.url) {
routeFounded = true;
var rt = this;
theRoute = rt;
return false;
}
});
if (routeFounded)
{
if (show)
{
visibleRoutes.push(theRoute);
}
else
{
visibleRoutes.remove(theRoute);
}
}
}
In Durandal 2.0.
You can enumerate the routes to find the one you wish to show/hide.
Then change the value of: nav property
Then run buildNavigationModel();
here is an example:
// see if we need to show/hide 'flickr' in the routes
for (var index in router.routes) {
var route = router.routes[index];
if (route.route == 'flickr') {
if (vm.UserDetail().ShowFlickr) { // got from ajax call
// show the route
route.nav = true; // or 1 or 2 or 3 or 4; to have it at a specific order
} else if (route.nav != false) {
route.nav = false;
}
router.buildNavigationModel();
break;
}
}
Durandal 2.0 no longer has the method visibleRoutes. I found that the following works for me.
router.reset();
router.map([
{ route: 'home', moduleId: 'home/index', title: 'Welcome', nav: true },
{ route: 'flickr', moduleId: 'flickr/index', title: '', nav: true }
])
.buildNavigationModel()
.mapUnknownRoutes('home/index', 'not-found');
This removes all previous routes, if you want to maintain current routes you could try using the router.routes property to rebuild the array of routes.
I had a similar requirement. If I were you, I would take another approach. Rather than adding/removing routes when application loads - get the right routes to begin with per user type.
Two options, (I use both)
1) have a json service provide the proper routes per user type, this approach would be good if you need to 'protect/obscure' routes... i.e. I don't want the route referenced on any client resource.
2) A simpler solution see Durandal.js: change navigation options per area
You can have a settings property identify the user type.
I hope this helps.
I had a similar problem: First, router.visibleRoutes() is an observable array. In other words, when you change its value, the routes automatically update. However, the items in this array are not observable, so to make a change you need to replace the entire array and not just make a change to a single item in it.
So, all you have to do is find which item in this array you want to remove, and then create a new array without this item, and set router.visibleRoutes() to this new array.
If, for example, you find out the it is the 3rd item, then one way of doing it is:
router.visibleRoutes(router.visibleRoutes().splice(2, 1))
Note that splice() returns a new array where an item is removed. This new array is put into router.visibleRoutes.