NGRX数据收集服务和数据服务,自定义端点可观察对象



我需要一个与ngrx/data中我的实体相关的自定义PUT请求,我想显示它,因为我不确定它是否准确…假设我有一个电影库,我可以通过PUT请求为电影添加标签。

我的数据服务:

export class MovieDataService extends DefaultDataService<typeof Movie> {
constructor(http: HttpClient, httpUrlGenerator: MovieHttpUrlGenerator, logger: Logger) {
super('Movie', http, httpUrlGenerator);
logger.log('Created custom Movie EntityDataService');
}
// CUSTOM METHODS APART FROM AUTO-CRETED BY COLLECTION SERVICE 
// Further handled in collection service
addTagToMovie(movieId: number, tagId: number) {
return this.execute(
'PUT', 
`https://external-api.com/movie/${movieId}/add_tag/${tagId}/`,
)
}
}

收集服务

constructor(
EntityCollectionServiceFactory: EntityCollectionServiceFactory,
private movieDataService: movieDataService,
) {
this.movieCollectionService = EntityCollectionServiceFactory.create<typeof Movie>('Movie');
}
getMovies() { this.movieCollectionService.getAll(); }
addTagToMovie(movieId: number, tagId: number) {
if (movieId && tagId) {
this.movieCollectionService.setLoaded(false)
this.movieCollectionService.setLoading(true)
this.movieDataService.addTagToMovie(movieId, tagId).pipe(
tap((updatedMovie: typeof Movie) => {
this.movieCollectionService.updateOneInCache(updatedMovie)
this.movieCollectionService.setLoading(false)
this.movieCollectionService.setLoaded(true)
})
).subscribe()
}
}

这是实现这一目标的合适方法吗?另外,订阅addtagtommovie是否会导致内存泄漏?如果没有它,它就不会触发,其他集合服务方法也不需要订阅(例如getAll()),是否也可以在不订阅的情况下实现它?

我试过上面描述的。

我的理解是订阅不需要发生在服务上,而只需要在服务上返回一个可观察对象,它将在组件上被订阅。

收集服务

constructor(
EntityCollectionServiceFactory: EntityCollectionServiceFactory,
private movieDataService: movieDataService,
) {
this.movieCollectionService = EntityCollectionServiceFactory.create<typeof Movie>('Movie');
}
getMovies() { this.movieCollectionService.getAll(); }
addTagToMovie(movieId: number, tagId: number) {
let output$ = of([]);
if (movieId && tagId) {
this.movieCollectionService.setLoaded(false)
this.movieCollectionService.setLoading(true)
output$ = this.movieDataService.addTagToMovie(movieId, tagId).pipe(
tap((updatedMovie: typeof Movie) => {
this.movieCollectionService.updateOneInCache(updatedMovie)
this.movieCollectionService.setLoading(false)
this.movieCollectionService.setLoaded(true)
})
)
}
return output$;
}

在组件中你可以做

private subscription: Subscription = new Subscription();
ngOnInit() {
this.subscription.add(
this.collectionService.addTagToMovie(1,2).subscribe()
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}

相关内容

  • 没有找到相关文章

最新更新