基于路线导航订阅Angular 2中的数据变化

jsg*_*pil 7 angular-routing angular

假设我有以下路线:

[
    {
        path: 'view',
        children: [
            {

                path: ':id',
                component: CustomerViewComponent,
                resolve: {
                    customerViewData: CustomerResolve,
                    edit: ViewRouteResolve // Returns false
                },
                data: {
                    other: false
                },
                children: [
                    {
                        path: 'edit',
                        resolve: {
                            edit: EditRouteResolve // Returns true
                        },
                        data: {
                            other: true
                        }
                    },
                    {
                        path: '',
                        data: {
                            other: false
                        }
                    }
                ]
            }
        ]
    },
    { path: '', component: CustomerListComponent }
]
Run Code Online (Sandbox Code Playgroud)

我想使用CustomerViewComponentfor /view/ 和 /view/1/edit

问题是我无法在我的组件中捕获此数据更改。我已经尝试过resolveordata并且我无法捕捉到任何变化......

此代码不会按预期触发:

this.route.data.subscribe(m => {
    debugger; // Triggers only once the view loads, then never again
});

// This triggers quite often, but the data is always stale.
this.router.events.subscribe(m => {
    console.log(this.route.snapshot.data['edit']);
    console.log(this.route.snapshot.data['other']);
    debugger;
});
Run Code Online (Sandbox Code Playgroud)

这可能是一个错误吗?我唯一的解决方法是查看事件 NavigationEnd 并分析 .url 字符串属性...

Dan*_*cal 5

尝试改为使用ActivatedRoutefrom@angular/router

this.activatedRoute.params.subscribe(params => {
    console.log(params['edit']);
    console.log(params['other']);
});
Run Code Online (Sandbox Code Playgroud)


Rad*_*adu 5

当监听router.eventssubscribe 回调时会得到几个不同类型的事件,每个路由改变多个。该ActivationStart是一个保存路径data。类似以下内容对我有帮助:

this.router.events.subscribe(event => {
  if (event instanceof ActivationStart) {
    let data = event.snapshot.data;
    this.titleService.setTitle(data['title'] || '_your_default_title_');
  }
})
Run Code Online (Sandbox Code Playgroud)