gpt4 book ai didi

Angular 路由解析器无法解析

转载 作者:行者123 更新时间:2023-12-03 15:08:38 25 4
gpt4 key购买 nike

我遇到了 Angular 的情况,其中路由数据解析器似乎准备正确返回数据,但解析从未发生。这特别奇怪,因为我有另一个组件的平行排列,并且在那里工作正常。

该应用程序通过 HTTP 检索有关一系列事件的数据。在 EventListComponent ,所有事件都由解析器返回以响应 /events ,并且组件正确显示它们。在 EventDetails组件,在我目前的安排中,我仍然通过 HTTP 检索所有事件,然后在解析器中响应 /events/[the event ID] ,选择应显示其详细信息的事件。 (这是来自 Pluralsight Angular Fundamentals 类(class),以防它听起来很熟悉。但我倾向于观看视频,然后按照自己的顺序完成它们,以巩固我头脑中的技能。)

远程事件.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 }
}
];

事件详细信息.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

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

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

enter image description here

在解析器激活的情况下:

enter image description here

这是解析器:

事件细节解析器.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 语句永远不会执行,就像我通过解析器运行请求之前一样。

有什么想法吗?

最佳答案

尝试使用
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));
}

}

看看这个 github discussion对这种行为。

关于 Angular 路由解析器无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56281571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com