本文介绍了在 Angular2 中订阅 router.events.subscribe 时如何从 Route 或 ActivatedRoute 获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当路由发生变化时,我都会尝试从路由器获取数据,但我没有成功.这里我设置了 asdf 属性

I'm trying to get the data from a Router whenever the Route changes but I'm not having success. Here I set the asdf property

@NgModule({
  bootstrap: [AppComponent],
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    OverviewComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', pathMatch: 'full', redirectTo: '' },
      { component: LoginComponent, path: 'login' },
      {
        children: [
          { path: '', pathMatch: 'full', redirectTo: 'overview', data: { asdf: 'hello' } },
          { component: OverviewComponent, path: 'overview', data: { asdf: 'hello' } },
        ], component: DashboardComponent,
        path: '',
      },
    ]),
  ],
})
export class AppModule { }

这里我可以在路由改变但 asdf 未定义时从路由器获取 URL :(

And here I can get the URL from the router when the route changes but asdf is undefined :(

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute, NavigationEnd } from '@angular/router';
@Component({
  selector: 'cs-map',
  styleUrls: ['map.component.css'],
  templateUrl: 'map.component.html',
})
export class MapComponent implements OnInit {
  private routerSub;

  constructor(private router: Router, private activatedRoute: ActivatedRoute) { }

  public ngOnInit() {
    this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
        let url = val.url;
        console.log(this.activatedRoute.snapshot.data['asdf']); // data is defined but asdf is not :(
      }
    });
  }
}

如何获取asdf的值?

我导航到 /overview

推荐答案

是这样的:

constructor(private router: Router,
        private activatedRoute: ActivatedRoute)
{

 this.router.events
        .filter(event => event instanceof NavigationEnd)
        .map(() => this.activatedRoute)
        .map(route => route.firstChild)
        .switchMap(route => route.data)
        .map(data => data['asdf'])
}
  1. 对于来自路由器的每个事件,我只过滤 NavigationEnd 事件
  2. 然后我将此事件映射到激活的路由(因为我想读取 NavigationEnd 上的激活路由的值).
  3. 我将激活的路由映射到 firstChild(使用 RouterModule.forRoot() 声明的第一个子节点).
  4. 然后创建一个 switchMap 来获取这条路由的数据,一个 switchMap 因为数据是一个可观察的.
  5. 最后,我将数据对象映射到我想要的键,在本例中为 asdf

这篇关于在 Angular2 中订阅 router.events.subscribe 时如何从 Route 或 ActivatedRoute 获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:38