Gre*_*olm 6 resolve angular2-routing angular2-observables angular
我遇到了 Angular 的情况,其中路由数据解析器似乎准备正确返回数据,但解析从未发生。这特别奇怪,因为我有另一个组件的平行排列,并且在那里工作正常。
该应用程序通过 HTTP 检索有关一系列事件的数据。在 中EventListComponent
,解析器返回所有事件以响应/events
,并且组件正确显示它们。在一个EventDetails
组件中,在我目前的安排中,我仍然通过 HTTP 检索所有事件,然后在解析器中响应/events/[the event ID]
,选择应该显示其详细信息的事件。(这是来自 Pluralsight Angular Fundamentals 课程,以防它听起来很熟悉。但我倾向于观看视频,然后按照我自己的顺序完成它们,以尝试巩固我头脑中的技能。)
远程事件.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;
}
Run Code Online (Sandbox Code Playgroud)
如果我不使用解析器,则 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 }
}
];
Run Code Online (Sandbox Code Playgroud)
事件详细信息.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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我在上面的路由列表中取消对resolver引用的注释,并在上面的组件代码中切换ngOnInit的两个副本中的哪一个被注释掉时,除了顶部的导航栏之外没有任何显示。
我启用了路由跟踪。不使用解析器:
在解析器激活的情况下:
这是解析器:
事件详细信息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;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,在返回 Observable 之前,我订阅了它,因此我可以在解析器中演示它将解析为的值——这是正确的事件对象值。免得你说在这里订阅它会阻止解析器解析,好吧,不,我在它已经无法工作后添加了它用于调试目的。当我将其注释掉时,我得到完全相同的结果(除了没有执行 console.log 调用):解析器永远不会解析。
这很奇怪,因为我对 Observable 的显式订阅表明它会产生正确的值。
确认这永远不会超过解析,请注意组件构造函数中的 console.log 语句永远不会执行,就像我通过解析器运行请求之前一样。
有什么想法吗?
asi*_*hmi 23
尝试使用
take(1)
或者 first
操作符来标记完成Observable
。解析在继续之前等待 Observable 完成。如果 Observable 没有完成, 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));
}
}
Run Code Online (Sandbox Code Playgroud)
看看这个 github上关于这种行为的讨论。
归档时间: |
|
查看次数: |
5934 次 |
最近记录: |