首页 > 解决方案 > 当解析在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 时停止路线更改并显示相同的视图。

标签: angular

解决方案


一种解决方案是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;
                       });

                         }

LIVE DEMO USING map


推荐阅读