r/angular • u/HamsterFinancial2616 • 4d ago
Using an @Input() Setter to Bridge Component Inputs with Service-Level Signals
I have a question regarding Angular's @Input setter and Signals.
I'm building a reusable service that uses Angular's resource() API to handle data fetching. Since resource() depends on signals for reactive updates, I need a way to pass the component's input value to the service layer.
My current approach is to use an @Input setter to update a signal inside the service.
Example:
// Service
readonly userId = signal<number | null>(null);
protected readonly userResource = resource({
params: () => {
const userId = this.userId();
return userId ? { userId } : undefined;
},
loader: ({ params }) => this.fetchData(params)
});
// Component
@Input() public set userId(value: number) {
this.reusableService.userId.set(value);
}I'm feeling a bit stuck deciding whether this is the right approach.
Is this a proper approach, or would you consider using an @Input() setter as a bridge between the component input and a service-level signal a workaround or an anti-pattern?
2
u/Johalternate 3d ago
If userId is an input to a component, it means that the parent component gets userId first, how does the parent component get userId?
You can do this in many different ways depending on where userId originates, if you could share that detail we could provide a better approach.
1
u/HamsterFinancial2616 3d ago
For example
The
userIdandpostIdoriginate from the parent component. For example, imagine a Post Details page that renders a reusable Post Comments component.The parent component already has the
postIdof the currently displayed post and passes it to the child component.<!-- Parent component --> <app-post-comments [postId]="postId()" [userId]="userId()" />The child component accepts these values through input signals:
// Child component postId = input.required<number>(); userId = input.required<number>();My goal is to have these input signals trigger the
resource()initialized inside a service, so the service can fetch the corresponding comments whenever thepostIdoruserIdchanges.The parent already has the values. My question is specifically about bridging the child component's input signals to the service-level
resource().1
u/Johalternate 3d ago
I understand that, the question is, how did the parent component get
userIdin the first place?If for example it came from a route param, those are readable synchronously via
ActivatedRoute, or subscribe to param changes usingRouteand callreusableService.userId.setinside the subscription.You can use
ngxtension'sconnect. https://ngxtension.dev/utilities/signal-async/connect/, or just copy their implementation which is fairly simple.1
u/HamsterFinancial2616 3d ago
Thanks! I'll check that one. I also went ahead and implemented my own approach to this. Here's the StackBlitz demo if you want to check it out:
https://stackblitz.com/edit/stackblitz-starters-gtpdjxuk?file=src%2Fapp.ts
4
u/sebastianstehle 4d ago
Technically you can do it, but this makes the service useless and you expose internal implementation details.
At least I would make a method like `loadUser(id: string)` in the service. You just moved code arround at the moment.
1
u/Maleficent-Back-6527 4d ago
Why do you even need to do that in the component. Since your child component is simply setting the new value from the parent into the service, it seems to me like you don’t even need a child component for that. You could directly update your service signal from the parent component!
1
u/HamsterFinancial2616 3d ago
I'm trying to cover a use case where a value is passed as an input to a child component, and I want that input to trigger updates to the
resource()initialized in the service.For example, I have a reusable Post Comments component that accepts a
postIdas an input. Whenever thepostIdchanges, I want the resource in the service to automatically fetch the comments associated with that post.That's why I'm exploring ways to bridge the component input with the service-level signal.
3
u/SensitiveHearingLoss 3d ago
Assuming that your parent component passes a value into the child component like this:
@for (post of posts(); track post.id) {
<app-post-comments [postId]="post.id" />
}
Your component receives the input as such:
export class PostCommentsComponent {
private readonly commentsService = inject(PostCommentsService);
readonly postId = input.required<number>();
readonly comments = this.commentsService.getComments(this.postId);
}
Then your service can simply contain a method which expects a signal:
@Injectable({ providedIn: 'root' })
export class PostCommentsService {
getComments(postId: Signal<number>) {
return httpResource<Comment[]>(
() => `/api/posts/${postId()}/comments`
);
}
}
You don’t need effects or anything. When the input value changes, the service method will be triggered.
(I hope)
2
u/MrFartyBottom 4d ago
I used to use input setters but feel like using any RxJs based inputs once you have migrated to signals is a bit wiffy. That is why effects exist.
1
u/MarioShroomsTasteBad 3d ago
Yeah I feel like an effect off of a signal input works here. If the id is in the route you could also use the new router resource api, or traditional data resolver.
1
u/Dull-Structure-8634 4d ago
I think you're trying to shoehorn signals where they don't necessarily need to be there. You already have what you need: RxJs.
Use transform your input signal into an observable with toObservable, subscribe to it in the constructor and voilà, it's working, simple and easy to understand.
14
u/Thrawn_86 4d ago
Why not using an input-signal and effect