首页 > 解决方案 > @ngrx/data 如何取消提供 getAll、getWithQuery、getByKey 的请求

问题描述

我在我的应用程序中使用 ngrx/data。

我有一个非常快速的应用程序。你可以在 UI 上选择一些东西,我需要更新我的视图。用户可以很快地做到这一点,在这种情况下,我不需要来自先前请求的任何先前数据。

但是当我添加 switchMap - 我的请求不会取消。

interface User {
  id: number;
  name: string;
}

@Component({
  selector: 'nrwl-test-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  test$ = new Subject();
  userEntity: EntityCollectionService<User>;
  constructor(private http: HttpClient, entityDefinition: EntityDefinitionService, entityServices: EntityServices) {
    entityDefinition.registerMetadataMap({
      User: {},
    });

    this.userEntity = entityServices.getEntityCollectionService<User>('User');
  }
  ngOnInit() {
    this.test$.pipe(
      switchMap(() => { 
        // return this.http.get('api/user') // switchMap works here
        return this.userEntity.getAll() // switchMap doesn't work here
      })
    ).subscribe();
  }

  onClick() {
    this.test$.next(Math.random());
  }
}

我有“@ngrx/data”:^0.10.2

但我在最新版本 11.0.1 上检查它 - 我有相同的行为。

我找到了一种解决方法,只需使用 httpClient 并在成功请求后更新我的 entityCache。但我不喜欢这种方法。

据我了解,实体服务总是返回 AnonymousSubject 而不是 Observable。这也是我无法取消请求的原因。但也许我可以以正确的方式做到这一点?

标签: angularrxjsngrx-entityswitchmapangular-ngrx-data

解决方案


ngrx-data base service 提供了一种cancel方法,可以用来请求取消查询或保存操作

在此处输入图像描述

您只需要在扩展的实体服务上调用该方法EntityCollectionServiceBase

在服务中创建一个生成correlationId的方法

public generateCorrelationId(): EntityActionOptions {
    this.currentCorrelationId = this.correlationIdGenerator.next();

    const entityActionOptions: EntityActionOptions = {
      correlationId: this.currentCorrelationId
    }

    return entityActionOptions;
  }

假设您希望能够取消您的 getWithQuery

let entityActionOptions = this.generateCorrelationId()
this.getWithQuery(queryParams, entityActionOptions);

然后取消你只需调用传递correlationId的方法

this.mileageTrackingManagmentService.cancel(entityActionOptions.correlationId)

推荐阅读