Angular 5中当Resolve返回无数据时如何阻止路由切换?
如何在Resolve返回空记录时阻止路由切换
要实现当Resolve返回的totalRecordsCount为0时阻止路由切换,你可以利用Angular Resolve守卫的核心特性:如果Resolve返回的Observable抛出错误,路由切换流程会自动终止。下面是具体的实现方案:
1. 修改Resolve服务,添加数据校验与错误抛出
在SomeResolveService的resolve方法中,通过RxJS操作符处理API返回的数据,当检测到空记录时主动抛出错误:
import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot } from '@angular/router'; import { Observable, throwError } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; import { SomeService } from './some.service'; @Injectable() export class SomeResolveService implements Resolve<any> { constructor(private someService: SomeService) { } resolve(route: ActivatedRouteSnapshot): Observable<any> { // 这里根据你的实际场景获取somedata,示例从路由查询参数中获取 const somedata = route.queryParams; return this.someService.search(somedata).pipe( map(response => { // 校验返回的记录总数 if (response.totalRecordsCount === 0) { // 抛出错误,触发路由切换终止 throw new Error('没有找到匹配的记录'); } // 数据正常,返回给目标组件使用 return response; }), catchError(err => { // 这里可以添加用户提示逻辑,比如用Toast组件显示友好提示 console.error(err.message); // 重新抛出错误,确保路由守卫感知到切换失败 return throwError(() => err); }) ); } }
2. (可选)全局捕获路由错误并提示用户
如果需要统一处理这类路由切换失败的场景,可以在AppComponent中监听Router的NavigationError事件,给用户展示友好提示:
import { Component } from '@angular/core'; import { Router, NavigationError } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { constructor(private router: Router) { this.router.events.subscribe(event => { if (event instanceof NavigationError) { // 匹配Resolve抛出的空记录错误 if (event.error.message === '没有找到匹配的记录') { // 这里替换成你项目中的提示组件,比如Toastr alert('没有找到匹配的记录,请调整搜索条件后重试'); } } }); } }
核心原理说明
Angular的Resolve守卫会等待其返回的Observable完成后,才会继续执行路由切换:
- 若Observable正常返回数据,路由会顺利切换到目标组件,数据可通过
ActivatedRoute.data在组件中获取; - 若Observable抛出错误,路由切换会被立即取消,页面将停留在当前路由。
这个方案完美契合你的需求:当搜索结果为空时,阻止路由跳转并保留当前视图。
内容的提问来源于stack exchange,提问作者Akshaya Jeevan
相关产品推荐
相关产品推荐

