FresherCodingAngular
Write a GET request with HttpClient and show the result in a component
Try answering first
Model answer
First enable HttpClient in the app config, then inject it and call get<T>(). The call returns an observable, and nothing is sent until something subscribes. toSignal subscribes for you and gives a signal the template can read.
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
}
// users.ts
interface User {
id: number
name: string
}
@Component({
selector: 'app-users',
template: `
@for (u of users(); track u.id) {
<li>{{ u.name }}</li>
} @empty {
<li>No users</li>
}
`,
})
export class Users {
private http = inject(HttpClient)
users = toSignal(this.http.get<User[]>('/api/users'), { initialValue: [] })
}
The generic get<User[]> types the response. toSignal also unsubscribes when the component is destroyed. You can instead use subscribe, or the async pipe on the observable.
Always enable HttpClient with provideHttpClient and type the response.
Key points
- Enable HttpClient with provideHttpClient
- get returns a cold observable that needs a subscriber
- toSignal subscribes and cleans up automatically
- The generic type describes the response
Likely follow-ups
- How would you show a loading state and an error message?
Common mistakes
- Calling get without subscribing and expecting a request
- Forgetting provideHttpClient and getting a NullInjectorError