angular - Refresh rxResource upon ngrx Action dispatch inside effect - Stack Overflow

Angular Version 19.1, trying out rxResource. Also, I am using ngrx, so I dispatch Actions when state ch

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.

  1. rxResource has a reload option. Triggering this option has the expected effect.
  2. 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信