Angular Version 19.1, trying out rxResource. Also, I am using ngrx, so I dispatch Actions when state changes happen.
What's working: The image is displayed correctly after fetching from the server. Also, the (not included) update mechanism for images in my backend works.
<imports omitted for brevity>
@Component{
...
}
export class ImageComponent{
identifier = input.required<Identifier | null>();
...
#getImage = (id: string) => this.imageService.getImage(id).pipe(map((imageUrl) => URL.createObjectURL(imageUrl)));
fetchedPicture = rxResource({
request: this.identifier,
loader: ({ request }) => {
if (request?.uuid) {
return this.#getImage(request.uuid);
} else return of(this.defaultImageResolver());
},
});
}
However, I also want to reload the rxResource when the content associated with the identifier changes.
- rxResource has a reload option. Triggering this option has the expected effect.
- There is an ngrx Action dispatched which indicates that there is a new image for a uuid.
The following code works as intended.
<imports omitted for brevity>
@Component{
...
}
export class ImageComponent{
identifier = input.required<Identifier | null>();
...
#getImage = (id: string) => this.imageService.getImage(id).pipe(map((imageUrl) => URL.createObjectURL(imageUrl)));
fetchedPicture = rxResource({
request: this.identifier,
loader: ({ request }) => {
if (request?.uuid) {
return this.#getImage(request.uuid);
} else return of(this.defaultImageResolver());
},
});
}
// new Code that triggers reload upon Success Dispatch
reloadImageAfterUpdate = effect(() =>
inject(Actions).pipe(
ofType(ImageActions.updateImageSuccess),
filter(({ imageUUID }) => imageUUID === this.identifier()?.uuid),
tap(() => this.fetchedPicture.reload())
)
);
However, I never used this pattern of listening to Actions in Components and the combination does not look like a best practice approach.
From what I understood about actions, they should only be used in effects or reducers. The image update is happening in an effect (which dispatches the Success Action), the rxResource is part of the component.
Is there a better conceptual approach to solve this problem?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745086657a4610446.html
评论列表(0条)