实现通用 @ngrx/data 服务是否可行,例如:
import { Injectable } from '@angular/core';
import { EntityCollectionServiceBase, EntityCollectionServiceElementsFactory } from '@ngrx/data';
@Injectable({providedIn: 'root'})
export class NgRxDataService<T> extends EntityCollectionServiceBase<T> {
constructor(entityName: string,
serviceElementsFactory: EntityCollectionServiceElementsFactory) {
super(entityName, serviceElementsFactory);
}
}
...并将其与各种组件中的多个预设数据类型对象/实体(例如:UserDTO、BookDTO 等)一起使用,例如以下示例:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { UserDto } from '../../../../data/definitions/dto/user.dto';
import { NgRxDataService } from '../../../../services/data/ngrx-data.service';
@Component({
selector: 'users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {
dataRecords$: Observable<UserDto[]>;
constructor(private dataService: NgRxDataService<UserDto>) {
this.dataRecords$ = dataService.entities$;
}
ngOnInit() {
this.getData();
}
getData() {
this.dataService.getAll();
}
// + CRUD functions
add(dataItem: UserDto) {
this.dataService.add(dataItem);
}
delete(dataItem: UserDto) {
this.dataService.delete(dataItem);
}
update(dataItem: UserDto) {
this.dataService.update(dataItem);
}
}
EntityCollectionServiceBase 是具体 EntityCollectionService 的基类。不能注入。它需要使用 EntityCollectionServiceFactory 来创建。通过通用方式接近它会不会有任何问题,或者是否需要为每个实体创建单独的服务(我试图避免)?