api调用失败后Angular 6解析器处理路由导航

时间:2018-09-09 14:10:04

标签: angular

我想使用路由解析器从服务器获取位置详细信息。

当数据库中没有匹配的场所ID时,服务器将以错误响应( 状态:-200, statusText:“ PlaceApiController,getPlace(),地点不存在。) 自定义通用重试逻辑服务器拦截器捕获到错误并引发“ throwError”可观察到的情况后。

server.interceptor.ts:

@Injectable()
export class ServerErrorsInterceptor implements HttpInterceptor {

constructor(private authService: AuthService, private loaderService: LoaderService) { }

/**
 * intercepts all server calls and retry them x times
 * before throwing an error.
 *
 * @param request
 * @param next
 *
 * @returns {Observable<HttpEvent<any>>}
 */
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
        .pipe(
            tap(() => this.loaderService.show()),                
            filter(event => event.type === 4),
            mergeMap(event => this.validateSuccessfulResponseStatus(event)),
            retryWhen(this.genericRetryStrategy()),
            catchError((error) => { 
                return throwError(error)
            }),
            finalize(() => this.loaderService.hide())
        );
  }
}

place-resolver.service.ts:

@Injectable()
export class PlaceResolverService implements Resolve<PlaceResultDtoModel> {
private getPlaceDtoModel: GetPlacePostDtoModel;

constructor(     
    private placeRepository: PlaceRepository,           
    private router: Router) 
{}

/**
 * @todo
 * 
 * @param route 
 * @param state 
 */
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<PlaceResultDtoModel> | any {
    const placeId = route.paramMap.get("id");

    this.getPlaceDtoModel = {
        id: +placeId
    }                       

    return this.placeRepository.getPlace(this.getPlaceDtoModel).pipe(
        map(placeDetails => {
            if (placeDetails) {
                return placeDetails;
            } else {
                this.router.navigate(["/places"]);
                return null;
            }
        },
        catchError(e => {
            const x = e;                
        }))            
    );
  }
}

当api get place调用返回错误时,我想导航回到位置列表,但是问题是resolve方法内部的'catchError'从未被调用过。控制台会显示以下消息:

ERROR Error: Uncaught (in promise): Object: {"status":-200,"statusText":"PlaceApiController, getPlace(), place does not exist."}

0 个答案:

没有答案