javascript - 从顶级组件中的延迟加载路由获取自定义路由数据

标签 javascript angular typescript

我正在使用 Angular 5,我似乎无法使用我的问题的其他答案中所述的方法从 ActivatedRoute 获取数据。

应用程序.routes.ts

export const AppRoutes = [
    {
        path : '',
        component: HomeView,
        pathMatch: 'full', data: {key: 'home', label: 'Home'}},
    {
        path : 'about',
        loadChildren: './+about/about.module#AboutModule'
    },
    {
        path : 'account/:id',
        loadChildren: './+account/account.module#AccountModule',
        canActivate: [AuthGuard],
        data: {key: 'account', label: 'My Account'}
    },
];

app.component.ts
@Component({
    selector: 'ou-app',
    templateUrl: 'app.component.html',
    styleUrls: ['../styles/main.scss'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
    constructor(
        private router: Router,
        private route: ActivatedRoute,
    ){}

    ngOnInit(){
        this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
            console.log('router events console... ', this.route);
        });
    }
}

我似乎无法从快照、root、children、firstChild 下的路由中获取数据,一切都是 null 或 undefined

最佳答案

问题是您不在您要查看的路线上。您需要通过子路线。这里有一个例子:Retrieving a data property on an Angular2 route regardless of the level of route nesting using ActivatedRoute

我能够使用上述链接中的信息修改您的代码,如下所示。

  router.events
    .filter(event => event instanceof NavigationEnd)
    .map(() => this.activatedRoute)
    .map(route  => {
      console.log(route.snapshot.data);
      while (route .firstChild) route = route.firstChild;
      return route;
    })
    .mergeMap(route => route.data)
    .subscribe(x => {
      console.log('router events console... ', x);
    });

使用此代码,我能够得到:

enter image description here

更新:使用 RxJs v5.5 及更高版本
ngOnInit() {
    this.router.events
        .pipe(
            filter((event) => event instanceof NavigationEnd),
            map(() => this.activatedRoute),
            map((route) => {
                while (route.firstChild) {
                    route = route.firstChild;
                }
                return route;
            }),
            mergeMap((route) => route.data))
        .subscribe((event) => console.log('router events console... ', event));
}

关于javascript - 从顶级组件中的延迟加载路由获取自定义路由数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49308304/

相关文章:

javascript - 更新状态后组件未重新渲染(调用了mapStateToProps)

javascript - 下划线将数组的键映射到另一个

javascript 变量显示在 console.log 中但不在浏览器输出中

angular - ionic3 在 span 标签 html 中使用 ref attr

javascript - Firebase - 从配置文件列表中按用户 ID 获取对象

javascript - 将我的自定义图标添加到 ionic 2 actionSheet 的按钮

javascript - 如何在 bobble 中配置 dc.bubbleOverlay() : min and max radius, 文本

node.js - 如何使用 Date.now() 修复日期错误

angular - 我可以使用 Angular i18n 来翻译 typescript 代码中的字符串文字吗

Angular2 如何在我的网址中传递问号和一些单词