来自解析器的 Angular 7 rxjs 订阅有什么问题

What's the problem in that Angular 7 rxjs subscription from a resolver

我写了一段简短的代码来尝试组件中的路由解析器和订阅。这是路由配置:

  {
    path: '',
    component: EventsComponent,
    resolve: {
      events: EventsResolverService
    }
  },
  ...

Resolver 简单地实现了 Resolve 接口:

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { EventInterface } from './event-interface';
import { EventsService } from './events.service';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EventsResolverService implements Resolve<Map<number, EventInterface>> {

  constructor(private eventsService: EventsService) { }

  public resolve(): Observable<Map<number, EventInterface>> {
    console.log('Resolver in progress');
    return this.eventsService.asObservable();
  }
}

然而,我用来获取事件地图的服务是可观察的:

  public asObservable(): Observable<Map<number, EventInterface>> {
    if (this.events.size) {
      return of(this.events);
    } else {
      this._hydrate();
      console.log('Events are : ' + this.events.size);
      return of(this.events);
    }
  }

最后,在组件的ngOnInit()方法中:

  public ngOnInit(): void {
    this.activatedRoute.data.subscribe(
      (events: Map<number, EventInterface>) => {
        console.log('Hi events resolved ' + events.size);
        this.eventsMap = events;
      },
      (error: any) => {
          console.log('Something went wrong : ' + error);
      }
    );
  }

控制台消息始终 return:未定义但在服务中,事件映射大小正确 returned:

那段代码有什么问题?

您正在以错误的方式处理 ActivatedRoute.data 发出的值。

this.activatedRoute.data.pipe(map(data=>data.events)).subscribe(
      (events: Map<number, EventInterface>) => {
        console.log('Hi events resolved ' + events.size);
        this.eventsMap = events;
      },
      (error: any) => {
          console.log('Something went wrong : ' + error);
      }
    );