router - 如何获取当前路由器配置 Aurelia 的标题

标签 router aurelia

我希望消息在我的应用程序的所有页面中持久存在,并在 View 模型和 View 绑定(bind)后进行设置。我的每个页面都有一个非常简单的模板。

<template>
    <h1>${message}</h1>
</template>

每个页面(“Page1”、“Home”、“Page2”)后面的代码都是空的。 这是我的 app.js

import {inject} from 'aurelia-framework';

export class App {

    configureRouter(config, router) {
        config.title = 'Pathways';

        config.map([
                { route: ['','home'], name: 'home', moduleId: 'home', nav: true, title:'Home' },
                { route: 'page1', name: 'page1',  moduleId: 'page1',    nav: true, title:'Page1' }

        ]);
        // Create a binding to the router object
        this.router = router;
    }
    attached() {
        this.message = this.router.currentInstruction.config.title;
    }
}

问题是,当我第一次加载应用程序时。 ${message} 为空。然后,当我导航到 page1 时,消息变为 Home !!我想可能是currentInstruction落后了,所以我又添加了一个页面。 Page2 如果你愿意的话,但事实证明,无论我在第一次导航后做什么,message 始终是 Home

因此,在应用初始化时消息为空白,然后在第一次导航时消息将始终保持Home

我的问题是,获取用户当前所在的每个页面的标题的“Aurelia”方式是什么?我认为在每个页面上注入(inject)路由器的成本很高

最佳答案

我可以看到两个选项:

第一个也是最简单的一个是使用一个监听 router.currentInstruction 的 getter 属性。例如:

@computedFrom('router.currentInstruction')
get message() {
  if (this.router.currentInstruction !== null)
    return this.router.currentInstruction.config.title;
}

运行示例 https://gist.run/?id=b01abe2859bc2bea1af0f8d21fc2045f

第二个选项是使用EventAggregator。例如:

attached() {
  this.subscription = this.ea.subscribe('router:navigation:success', () => {
      this.message = this.router.currentInstruction.config.title;
  });
}

detached() {
  this.subscription.dispose(); //remember to always dispose the subscription
}

运行示例https://gist.run/?id=7d30d4e8d479cc209ca9013e10e91505

他们说我们应该尽量避免 EventAggregator。所以,我会选择第一个选项。

关于router - 如何获取当前路由器配置 Aurelia 的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046434/

相关文章:

aurelia - 从 View 模型调用自定义属性方法

node.js - 如何使用 aurelia 让 webpack 与 Electron 一起工作?

ubuntu - 尝试托管服务器以进行外部访问 - Apache、VirtualBox 和端口转发

angular - router-outlet 在页面上占用额外空间(Angular 2)

javascript - 使用静态 HTML 文件的主干路由

php - 使用 API pref 管理 IPTables。 PHP

javascript - 如何使用路由器和内置/自定义属性在 aurelia 中创建下拉菜单?

node.js - 使用自定义属性的 aurelia 自定义插件 - 找不到自定义属性

javascript - 如何使用 Fetch 和 Aurelia 打印发送表单数据的结果消息

linux - 通过外部 IP 地址或 DynDNS url 查看设备内网页面