angular - 当解析在Angular 5中没有返回数据时停止路由更改
问题描述
解析服务返回空记录时如何停止路由?我想停止路由更改取决于解析数据。请检查以下代码。
路线配置——
{
path: 'search',
component: SomeComponent,
resolve: { searchData: SomeResolveService }
}
一些.resolve.ts
@Injectable()
export class SomeResolveService implements Resolve<any> {
constructor(private someService: SomeService) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.someService.search(somedata);
}
}
一些.service.ts
search(somedata): Observable<any> {
return this.http
.post(`${environment.apiPrefix}/search`, somedata);
}
上述服务响应返回以下 json -
{
records: [],
totalRecordsCount: 0
}
我想在 totalRecordsCount 为 0 时停止路线更改并显示相同的视图。
解决方案
一种解决方案是Observable
使用 RXJS Utility Operator点击并根据某些条件重新导航。
RxJS 的点击操作符查看可观察的值,对这些值做一些事情,然后传递它们。
tap
回调不会触及值本身。
例子
@Injectable()
export class SomeResolveService implements Resolve<any> {
constructor(private someService: SomeService,Private route:router) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.someService.search(somedata).pipe(tap((response)=>{
//you could use some logic to check your totalRecordsCount here
let total= //some logic to extract totalRecordsCount
if(!total)
{
this.route.naviagte[('/yourRoute')]
}});
}
LIVE DEMO USING tap
或者您可以使用 RXJSmap
运算符来拦截响应并根据某些条件重新导航。
尽管此运算符用于在将响应发送到应用程序之前对其进行修改,但我认为将其用于此目的没有任何危害。
例子
@Injectable()
export class SomeResolveService implements Resolve<any> {
constructor(private someService: SomeService,Private route:router) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.someService.search(somedata).pipe(map((response)=>{
//you could use some logic to check your totalRecordsCount here
let total= //some logic to extract totalRecordsCount
if(!total)
{
this.route.naviagte[('/yourRoute')];
return null;
}
return response;
});
}
推荐阅读
- angular - 在构建开发版本时“生成浏览器应用程序包”消息
- python - 如何为生产和登台服务器动态更改 Django 项目 settings.py
- python - 构建 Relu 层:TypeError:“builtin_function_or_method”对象不支持项目分配
- sql - 将两个字符串与尾随的“空白”字符串进行比较
- ios - 与使用 UIViewController + UICollectionView 相比,使用 UICollectionViewController 是否合适?
- react-native - React Native Flatlist - 使用 Redux 作为数据属性......当 Redux 状态更改时不会重新渲染
- javascript - 从 x 轴莫里斯图中删除重复值
- python - 用于字典迭代的python MPI
- c++ - 如何在 CMFCMenuBar 上动态插入菜单?
- git - 你能检查一个 git commit 的时间戳是否是从 GitHub 编辑的吗?鉴于这些提交是在项目上传之前完成的