角路由解析器无法解析

时间:2019-05-23 19:09:39

标签: angular angular2-routing angular2-observables resolve

我在Angular遇到一种情况,即路由数据解析器似乎准备正确返回数据,但是解析永远不会发生。尤其奇怪,因为我对另一个组件进行了并行布置,并且在那里工作正常。

应用程序通过HTTP检索有关事件数组的数据。在EventListComponent中,解析器将响应/events返回所有事件,并且组件会正确显示它们。在EventDetails组件中,按照我目前的安排,我仍在通过HTTP检索所有事件,然后在解析器中响应/events/[the event ID],选择应该显示其详细信息的事件。 (如果听起来很熟悉,这是来自Pluralsight Angular基础知识课程。但是,我倾向于观看视频,然后按照自己的顺序进行学习,以巩固自己的头脑。)

remote-event.service.ts

import { Injectable, EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { IEvent } from './event.model';

@Injectable()
export class RemoteEventService {

  constructor(
    private http: HttpClient
  ) {}

  getEvents(): Observable<IEvent[]> {
    return this.http.get<IEvent[]>('/api/ngfdata/events.json');
  }

  getEventById(id: number): Observable<IEvent> {
    console.log(`In getEventById: id = ${id}`);
    const emitter = new EventEmitter<IEvent>();
    this.getEvents().subscribe(
      (events) => {
        emitter.emit(events.find((event) => event.id === id));
      }
    );
    return emitter;
  }

export interface ISessionSearchResult {
  eventId: number;
  sessionId: number;
  sessionName: string;
}

如果我不使用解析器,则EventDetails组件可以正常工作。这有效:

eventRoutes (这是从/ events /分支出来的子路由)

import { Routes } from '@angular/router';
import { EventListComponent, EventDetailsComponent,
  CreateEventComponent, UnsavedNewEventGuard,
  EventListResolver, EventDetailResolver
} from './index';

export const eventRoutes: Routes = [
  { path: 'create', component: CreateEventComponent,
    canDeactivate: [UnsavedNewEventGuard]
  },
  { path: ':id', component: EventDetailsComponent/*,
    resolve: { event: EventDetailResolver }*/
  },
  { path: '', component: EventListComponent,
    resolve: { events: EventListResolver }
  }
];

event-details.component.ts

import { Component, Input, OnInit, inject, Inject } from '@angular/core';
import { RemoteEventService } from '../shared/remote-event.service';
import { ActivatedRoute, Params } from '@angular/router';
import { IEvent } from '../shared/event.model';
import { TOASTR_TOKEN } from 'src/app/common/3rd-party/toastr.service';

@Component(
  {
    selector: 'event-detail',
    templateUrl: './event-details.component.html',
    styles: [`
      .container { padding-left: 20px; padding-right: 20px; }
      .event-image { height: 100px; }
      .btn-group:first-child {
        margin-right: 24px;
      }
      .btn-group {
        border: medium solid green;
      }
      .btn-group .btn:not(:first-child) {
        border-left: thin solid green;
      }
    `]
  }
)
export class EventDetailsComponent implements OnInit {
  event: IEvent;
  filterBy = 'all';
  sortBy = 'name';

  constructor(
    private eventService: RemoteEventService,
    private route: ActivatedRoute,
    @Inject(TOASTR_TOKEN) private toast
    ) {
      console.log('In EventDetailsComponent.constructor');
    }

/*   ngOnInit() {
    console.log('At start of EventDetailsComponent.ngOnInit');
    this.event = this.route.snapshot.data['event'];
    console.log('At end of EventDetailsComponent.ngOnInit');
  }
*/

  ngOnInit() {
    console.log('At start of EventDetailsComponent.ngOnInit');
    this.route.params.forEach((params: Params) => {
      this.eventService.getEventById(+params.id).subscribe(
        (event) => this.event = event
      );
    });
    console.log('At end of EventDetailsComponent.ngOnInit');
  }

  flashSessionSummary(message: string) {
    this.toast.info(message);
  }
}

enter image description here

当我在上面的路由列表中取消注释解析器引用并在上面的组件代码中切换注释掉ngOnInit的两个副本中的哪一个时,除了顶部的导航栏之外,什么都没有显示。

我启用了路由跟踪。不使用解析器:

enter image description here

解析器处于活动状态:

enter image description here

以下是解析器:

event-detail-resolver.service.ts

 import { Injectable, Input } from '@angular/core';
import { RemoteEventService } from '../shared/remote-event.service';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { IEvent } from '../shared/event.model';

@Injectable()
export class EventDetailResolver implements Resolve<IEvent> {

  constructor(
    private eventService: RemoteEventService
  ) {}

  resolve(route: ActivatedRouteSnapshot) {
    console.log(`In resolve(): id = ${route.params.id}`);
    const e = this.eventService.getEventById(+route.params.id);
    console.log(`The observable that resolve() is about to return: ${JSON.stringify(e)}`);
    e.subscribe((evt) => console.log(`The value that the observable resolves to: ${JSON.stringify(evt)}`));
    return e;
  }

}
如您所见,在返回Observable之前,我已订阅它,因此我可以在解析器中演示它将解析为的值-这是正确的事件对象值。免得您说在这里订阅它会阻止解析器解析,嗯,不,我补充说,出于调试目的,之后它已经不起作用了。当我将其注释掉时,我得到的结果是完全相同的(除了不执行console.log调用):解析器从不解析。

这很奇怪,因为我对Observable的显式订阅表明它打算产生正确的值。

确认这永远不会解决,请注意,组件的构造函数中的console.log语句从未执行过,就像我通过解析器运行请求之前一样。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试使用

take(1)first

运算符以标记Observable的完成。解决方法要先等待Observale完成,然后再继续。如果Obserable尚未完成,则resovler将不会返回。

您的代码将如下所示:

import { Injectable, Input } from '@angular/core';
import { RemoteEventService } from '../shared/remote-event.service';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { take } from 'rxjs/operators';
import { IEvent } from '../shared/event.model';

@Injectable()
export class EventDetailResolver implements Resolve<IEvent> {

  constructor(
    private eventService: RemoteEventService
  ) {}

  resolve(route: ActivatedRouteSnapshot) {
    console.log(`In resolve(): id = ${route.params.id}`);
    const e = this.eventService.getEventById(+route.params.id);
    console.log(`The observable that resolve() is about to return: ${JSON.stringify(e)}`);
    e.subscribe((evt) => console.log(`The value that the observable resolves to: ${JSON.stringify(evt)}`));
    return e.pipe(take(1));
  }

}

有关此行为,请查看此github discussion