Ngrx/data getWithQuery 不会根据我给它的查询过滤数据

问题描述

当我尝试像这样查询已批准的标签时,它返回所有条目而不是已批准的条目

getAllApprovedTags(): Observable<Array<Tag>> {
    return this.tagsService.getWithQuery({tagStatus:'Approved'});
}

我也尝试了以下

getAllApprovedTags(): Observable<Array<Tag>> {
        return this.tagsService.getWithQuery("tagStatus='Approved'");
}

以下内容

getAllApprovedTags(): Observable<Array<Tag>> {
        return this.tagsService.getWithQuery("tagStatus=Approved");
}

我正在使用

Angular CLI: 11.0.1
Node: 10.19.0
OS: linux x64
NgRx/Data: 10.1.2

后端是

环回 4 和 MongoDB

我有以下型号

export class Tag {
  constructor(
    public id: string,public tagName: string,public tagDescription: string,public tagStatus: string,public createdDate: Date,){ }
}

我的实体配置如下

const entityMetadata: EntityMetadataMap = {
  Tag: {},};

const pluralNames = {
  Tag: 'Tags',};

export const entityConfig = {
  entityMetadata,pluralNames,};

服务类如下所示

@Injectable({
  providedIn: 'root'
})
export class TagsService  extends EntityCollectionServiceBase <Tag> {
  constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
    super('Tag',serviceElementsFactory);
   }
}

数据如下

Example Data

解决方法

getWithQuery 只是将查询参数添加到端点 URL:

/api/tags/?tagStatus=Approved

即使设置了服务器来处理这个问题,它也可能不是您想要做的。需要更多上下文,但根据您的问题,听起来您似乎希望将 Tag 实体的​​集合过滤为状态为“已批准”的实体。如果是这样,也许您想要 filterFn (docs here):

const entityMetadata: EntityMetadataMap = {
  Tag: {
    filterFn: (tags: Tag[],status: TagStatus) => {
      return tags.filter(tag => tag.status === status);
    }
  },};

在你的组件中:

getAllApprovedTags(): Observable<Array<Tag>> {
  this.tagService.setFilter(TestStatus.Approved); // or 'Approved' if you don't use an enum
  return this.tagsService.filteredEntities$;
}

但是,根据我的理解,使用该过滤器的任何其他地方也将被更改,因此对于您的用例而言,使用 selector 可能会更好。

@Injectable({
  providedIn: 'root'
})
export class TagsService extends EntityCollectionServiceBase <Tag> {

  approvedTags$ = this.entities$.pipe(select(selectApprovedTags));

  constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
    super('Tag',serviceElementsFactory);
  }
}
// selectors

export const selectApprovedTags = createSelector(
  (tags) => tags,(tags: Tag[]) => tags.filter(tag => tag.status === TagStatus.Approved)
);

(基于我在他们的 demo 中看到的内容,高于 selector 实现)