我将主题作为可观察对象从服务传递给解析器。当一个 http 请求完成或当它发现它需要的数据被缓存时,服务可能会完成 observable。在第二种情况下,数据被缓存,看起来 observable 完成得太早了,因为路由转换没有发生。如果我将 requestSubject.complete() 放在 setTimeout 中并有一些超时,它可以工作,否则它不会。
//resolve function from resolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
const id = +route.paramMap.get('id');
const language = route.queryParamMap.get('language');
const request = this.service.get(id, language);
request.pipe(share()).subscribe(
() => {},
() => { this.router.navigateByUrl(AppRoutingConfig.search); });
return request;
}
//the service get function
get(id: number, language: string): Observable<any> {
const requestSubject = new Subject();
if (!isDataCached(id)) {
const url = `some url`;
const sub = this.http.get(url).subscribe((item: any) => {
requestSubject.next(1);
}, () => {
requestSubject.error(0);
}, () => {
requestSubject.complete();
});
} else {
requestSubject.complete();
}
return requestSubject.asObservable();
}