最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论