如何在解析服务返回空记录时停止路由?我想根据解析数据停止路线更改。请查看以下代码。
路线配置 -
{
path: 'search',
component: SomeComponent,
resolve: { searchData: SomeResolveService }
}
some.resolve.ts
@Injectable()
export class SomeResolveService implements Resolve<any> {
constructor(private someService: SomeService) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.someService.search(somedata);
}
}
some.service.ts
search(somedata): Observable<any> {
return this.http
.post(`${environment.apiPrefix}/search`, somedata);
}
上述服务响应返回json -
以下{
records: [],
totalRecordsCount: 0
}
我想在totalRecordsCount为0并且显示相同的视图时停止路线更改。
答案 0 :(得分:1)
一种解决方案是使用RXJS实用程序运算符 tap 进入Observable
并根据某些条件重新导航。
RxJS tap操作符查看可观察值 具有这些价值观的东西,并传递它们。
tap
回拨。{1}} 不接触价值观。
示例强>
@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
强>
或者您可以使用RXJS map
运算符来拦截响应并根据某些条件重新导航。
虽然此运算符用于在将响应发送到应用程序之前修改响应但我没有看到任何伤害用于此目的。
示例强>
@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;
});
}
<强> LIVE DEMO USING map
强>