我有一个组件,用户可以在其中 Select 要生成的报告类型.
Component.ts函数如下所示:
generateReport(reportType, projectReport) {
this.showSpinner = true;
if(reportType === 'project-weekly-report')
this.router.navigate(['/weeklyReport', projectReport]).catch<any>(this.handleError.bind(this));
else this.router.navigate(['/monthlyReport']).catch<any>(this.handleError.bind(this));
}
它转发到的这条路由有一个使用解析器来处理报表加载的组件.组件的ngOnInit()如下所示:
ngOnInit(): void {
this.report = this.route.snapshot.data['projectWeeklyReport'].result;
}
解析器如下所示:
@Injectable()
export class ProjectWeeklyReportResolve implements Resolve<any> {
constructor(private reportService: ReportService, private http: HttpClient) {}
resolve(route: ActivatedRouteSnapshot) {
return this.reportService.getProjectWeeklyReport(route.paramMap.get('projectName'));
}
}
此解析器调用服务中的以下函数:
getProjectWeeklyReport(projectName) {
var workerUrl = this.reportUrl + '/weeklyreport/projectname/' + projectName + '/job/';
return this.http
.get<any>(this.reportUrl + '/weeklyreport/projectname/' + projectName, this.getAuthOptions(true))
.pipe(
switchMap(workerId => this.pollFor(workerId, isWorkerCompleted, isWorkerFailed, 2000, workerUrl)),
catchError(this.handleError)
);
}
此方法访问服务器以通知它开始生成报告.由于生成报告需要一些时间,因此该作业(job)已被分派给工作人员作业(job).然后,我们轮询此工作人员作业(job),以判断报告是否已完成生成报告.
轮询函数如下所示:
type CustomPollOperator = (data: any, condComp: (d) => boolean, condFail: (d) => boolean, ms: number, url: string) => Observable<any>
const isWorkerCompleted = w => w.result;
const isWorkerFailed = w => w.failedReason;
//Convenience method for polling operation
pollFor: CustomPollOperator = (data, condComp, condFail, ms, url) => {
let shouldPoll = true;
return interval(ms)
.pipe(
tap(() => console.warn('polling', shouldPoll)),
takeWhile(() => shouldPoll),
switchMap(() => this.http.get<any>(url + data.id, this.getAuthOptions(true))),
tap(res => {
if(condComp(res)) {
shouldPoll = false;
}
else if(condFail(res)) {
shouldPoll = false;
throw new Error('Polling worker job failed');
}
}),
catchError(this.handleError)
)
}
在我将Angular 从9更新为14之前,当SwitchMap和CustomPollOperator完成其工作时,解析器将收到完成的报告.
但是,在更新Angular 版本之后,解析器不会等待轮询完成,而是在作业(job)的第一个请求开始后立即加载页面.
你知道是什么导致了这个问题吗?当不涉及解析器时,我在其他地方使用相同的代码,并且它的功能与以前一样.
首先要感谢大家!