1

I use ngrx/data in my app.

I have a very quick application. You can select something on UI and I need to update my view. A user can do it very quickly, I do not need any previous data from previous requests in that case.

But when I add switchMap - my request doesn't cancel.

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());
  }
}

I have "@ngrx/data": ^0.10.2

but I check it on the latest version 11.0.1 - and I have the same behavior.

I found a workaround just use httpClient for it and after the success request I update my entityCache. But I do not like this approach.

As I understand entity service return always AnonymousSubject instead of Observable. And it is a reason why I can not cancel my request. But maybe I can do it in the right way?

1 Answers1

1

ngrx-data base service offers a cancel method that can be used to request to cancel a query or save operation

enter image description here

You just need to call that method on an entity service that extends EntityCollectionServiceBase

Create a method in the service that generates the correlationId

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

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

    return entityActionOptions;
  }

Lets say you want to make be able to cancel you getWithQuery

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

then to cancel you just call the method passing the correlationId

this.mileageTrackingManagmentService.cancel(entityActionOptions.correlationId)
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99