在Angular2中订阅router.events.subscribe时如何从Route或ActivatedRoute获取数据? [英] How to get data from Route or ActivatedRoute when subscribing to router.events.subscribe in Angular2?

查看:17
本文介绍了在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. 然后我把这个事件映射到activatedRoute(因为我想在NavigationEnd上读取activatedRoute的值).
  3. 我将 activateRoute 映射到 firstChild(使用 RouterModule.forRoot() 声明的第一个孩子).
  4. 然后做一个 switchMap 来获取这条路由的数据,一个 switchMap 因为 data 是一个 observable.
  5. 最后我将数据对象映射到我想要的键,在本例中为 asdf

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆