我的系统中有一个用户实体,以下路由从服务器获取它并显示其详细信息:
routerConfiguration.map([
// ...
{route: 'user/:id', name: 'user-details', moduleId: './user-details'}
]);
Run Code Online (Sandbox Code Playgroud)
现在我想为所显示的用户显示一个编辑表单。我有以下要求:
第一次尝试
我尝试将编辑表单定义为单独的页面:
routerConfiguration.map([
// ...
{route: 'user/:id/edit', name: 'user-edit', moduleId: './user-edit'}
]);
Run Code Online (Sandbox Code Playgroud)
这通过了 #1 和 #3 要求,但在打开编辑表单时必须再次加载用户。
我不知道有什么方法可以在路线之间走私一些自定义数据。如果我可以将预加载的用户实例传递到编辑路由,并且编辑组件将使用它,或者在未给出的情况下加载一个新实例(例如,用户直接访问 URL),那就完美了。我只找到了如何以一种稍微有点hacky的方式将字符串传递给路由。
第二次尝试
我决定在模态中显示编辑表单,并在有?action=editGET 参数时自动显示。受此问题和此问题启发的代码:
export class UserDetails {
// constructor
activate(params, routeConfig) {
this.user = /* fetch user */;
this.editModalVisible = params.action == 'edit';
}
}
Run Code Online (Sandbox Code Playgroud)
当用户单击该Edit按钮时,将执行以下代码:
displayEditForm() {
this.router.navigateToRoute('user/details', {id: this.user.id, action: 'edit'});
this.editModalVisible = true;
}
Run Code Online (Sandbox Code Playgroud)
这会传递 #1(编辑 url 为user/123?action=edit)和 #2(用户实例仅加载一次)。但是,当用户单击Back浏览器按钮时,URL 会根据需要从 更改user/123?action=edit为user/123,但我不知道如何检测它并隐藏编辑表单(activate不会再次调用该方法)。因此,该解决方案不符合#3 要求。
编辑:
事实上,我发现我可以使用事件聚合器检测 URL 更改并隐藏编辑表单:
ea.subscribe("router:navigation:success",
(event) => this.editModalVisible = event.instruction.queryParams.action == 'edit');
Run Code Online (Sandbox Code Playgroud)
但我仍然想知道是否有更好的方法来实现这一目标。
问题是
如何以干净直观的方式应对这种情况?
添加一个 User 类作为模型并使用依赖注入在视图模型中使用它怎么样?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
459 次 |
| 最近记录: |