从我导航到 router.events.subscribe 内部的组件获取变量

Get variable from component which I navigated to inside of router.events.subscribe

我正在创建应用程序历史记录功能,并且需要从每个组件获取一个变量,该变量是在每个组件初始化时从 http 调用中获取的。

目前我只是像这样在我的 AppComponent 中订阅 router.events

export class AppComponent {
    constructor(private router: Router, private historyService: HistoryService) {
        this.router.events
            .filter(e => e instanceof NavigationEnd)
            .subscribe((routerEvent) => {
                console.log('Storing History Entry: ', routerEvent);
                this.historyService.saveEntry(routerEvent);
            });
    }
}

有没有办法让我从这个下的每个组件中获取一个变量并将其传递给历史服务,以便历史可以包含这个变量?

您可以在组件之间使用共享服务并使用该服务属性:

export class AppComponent {
    constructor(private router: Router, private historyService: HistoryService) {
        this.router.events
            .filter(e => e instanceof NavigationEnd)
            .subscribe((routerEvent) => {
                console.log('Storing History Entry: ', routerEvent);
                this.historyService.saveEntry( this.shared.service.getMyVar());
);
            });
    }
}

甚至直接从 historyService 调用 getMyVar。

共享服务

myVar:any;
getMyVar(){
 return this.MyVar;
}
setMyVar(value){
 this.myVar=value;
}

组件

this.sharedService.setMyVar(value)

另一个解决方案是使用本地存储,但它有限制以防用户禁用本地存储

如果是固定值,可以使用路由配置上的数据属性,为每条路由提供一点数据。

{
    path: 'products',
    data: { someBitofInfo: 'info'},
    component: 'ProductComponent'
},

数据 属性 是只读的,因此您只能将其用于固定值。但是你可以为每个路径定义不同的固定值。

如果这不是一个选项(数据不固定),那么您可以将名称添加到 URL 作为可选参数或查询参数……缺点是它会显示在地址栏中。但是,如果您不关心您的地址栏 URL 是什么样子,那么它是您的一个选择。