angular - @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。这也是我无法取消请求的原因。但也许我可以以正确的方式做到这一点?
解决方案
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)
推荐阅读
- javascript - 使用 jquery 在元素箭头上删除类
- cypress - 如何检查复选框是否处于不确定状态(既未选中也未选中)?
- python - if then else 在 DataFrame 的 Regex 中
- elasticsearch - 弹性搜索中范围查询中boost的作用是什么
- python - Pandas:使用另一个分隔符列连接多列,并避免空白值的额外分隔符
- c - Cortex M3、STM32、thumb2:我的 inc 和 dec 操作不是原子的,但应该是原子的。这里有什么问题?
- javascript - “连接”上的 Socket.io 服务器未触发,客户端事件未触发也是如此
- reactjs - 反应任何道具解构
- runit - 没有暂停的runit启动脚本
- python - Pydantic cpecify 配置文件