Reputation: 634
How to stop routing when resolve service returns empty records? I want to stop the route change depend on resolve data. Please check below code.
route config -
{
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);
}
The above service response returns below json -
{
records: [],
totalRecordsCount: 0
}
I want to stop route change when the totalRecordsCount is 0 and show the same view.
Upvotes: 2
Views: 826
Reputation: 12036
One Solution is Tapping into the Observable
using RXJS Utility Operator tap and re-navigating based on some condition.
The RxJS tap operator looks at the observable values, does something with those values, and passes them along. The
tap
call back doesn't touch the values themselves.
Example
@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
Or you could use RXJS map
operator to Intercept the response and re-navigate based on some condition.
Though this operator is used to modify the response before sending it to the application I don't see any harm in using it for this purpose.
Example
@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;
});
}
Upvotes: 2