In a component, I am accessing item_id as input parameter. Where can I call toSignal() or .subscribe() to service method, if it is not allowed inside constructor / ngOnInit() effect()?
item_id = input<string>();
constructor() {
effect(() => {
const itemId = this.item_id();
if (itemId !== undefined) {
this.itemSvc.setItemId(itemId); // setup the observable service with itemId
this.itemSvc.itemDetails().subscribe({ }) // subscribe to get the data about particular itemId
});
}
});
P.S. computed() is also not working. Do you know the reason why ?
ItemData$ = computed(() => {
const itemId = this.item_id();
if (itemId !== undefined) {
this.itemSvc.setItemId(itemId);
return this.itemSvc.itemDetails();
}
return signal<Item | null>(null); });
You can just use toObservable
for this. To Convert to observable then use switchMap
to switch to the API observable you need, this will react when the signal changes.
item_id = input<string>();
itemDetails = toObservable(this.item_id).pipe(
switchMap((itemId: string) => {
if (itemId !== undefined) {
this.itemSvc.setItemId(itemId); // setup the observable service with itemId
return this.itemSvc.itemDetails();
}
return of([]);
})
);