I need to fetch some posts. We will use the httpResource. HttpClient returned observables but this one is reactive wrapper around HttpClient. The response we get is a signal.
page = signal(0)
content = httpResource(() => ({
url: 'https://jsonplaceholder.typicode.com/posts',
params: {
page: this.page()
}
}));
We can render the content in template as {{ content.value() }}
But there is new inquiry.
We need filter by specific user, No problem we can pass params. The params will come from Router, which we can easily fetch with in our component by enabling withComponentInputBinding. In short it binds Router state to the component input.
https://localhost:4000/posts?userId=332
Our component becomes
import { input } from '@angular/core';
page = signal(0)
userId = input()
content = httpResource(
() => ({
url: 'https://jsonplaceholder.typicode.com/posts',
params: {
page: this.page(),
userId: this.userId(),
}
));
We use input to get userId from route as signal which makes our content resource reactive.
What happens when we change user?
We get the new value for userId input, this will in turn re run the content httpResource. Our template will be updated.
We have pagination feature on the page to list user post, we have navigate to page 6 of User A. Now we switched the to User B. We need to reset the page to page 1.
No problem we can easily do that using effect to react to signal and update another signal.
#resetPage = effect(() => {
const user = this.userId()
this.page.set(0)
})
This ensures we have pagination reset to page 1 when user selection is updated.
But there is caveat to our way of using effect. In fact angular docs on Use cases of effect no where mentions to use effects just to update another signal.
Its best uses cases are DOM read writes, syncing local storage among others.
What if we can stay in Signals land.
Don’t worry Angular have a better solution in the form of LinkedSignal. A signal can derive a dependent and it the same time it can be write able.
page = linkedSignal({
source: this.userId,
computation: () => 0
})
One less effect in our signal reactive paradigm. LinkedSignal is a missing puzzle. It gives the default value to page. We are allowed to change page on demand. When userId is updated the page is automatically reset to initial state.
