Pass values to route

时间:2015-12-14 17:57:17

标签: aurelia aurelia-router

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)?

2 个答案:

答案 0 :(得分:11)

好的,所以我找到了一种方法来实现更接近我想要的东西:

目标:将数据传递到路线,而不会在位置栏中公开它们。

假设我们有一个用户列表,我们希望将username传递给用户的个人资料页面,而不将其定义为查询参数。

在视图模型中,首先注入Router,然后将数据添加到目标路由器:

goToUser(username) {
    let userprofile = this.router.routes.find(x => x.name === 'userprofile');
    userprofile.name = username;
    this.router.navigateToRoute('userprofile');
}

现在,当路线更改为userprofile时,您可以将路线设置作为activate方法的第二个参数进行访问:

activate(params, routeData) {
    console.log(routeData.name); //user name
}

答案 1 :(得分:1)

对于那些@Sayem的答案无效,您可以将任何其他数据(甚至对象)放入设置属性中,如下所示:

let editEmployeeRoute = this.router.routes.find(x => x.name === 'employees/edit');
editEmployeeRoute.settings.editObject = employeeToEdit;
this.router.navigateToRoute('employees/edit', {id: employeeToEdit.id});

因此editObject将在另一侧传递:

activate(params, routeConfig, navigationInstruction) {
    console.log(params, routeConfig, navigationInstruction);
    this.editId = params.id;
    this.editObject = routeConfig.settings.editObject;
}

希望这可以帮助其他人遇到与我相同的问题。 TG。