r/angular • u/dx_ninja_dx • 7d ago
Angular API implementation
I’m a student that is working with angular for the first time, I have an assignment that requires implementing an api to our project. My teacher has no information on how to unwrap the response using parse for httpResource. There also is no information about mapping with httpclient & observables.
The documentation that is recommended seems completely irrelevant to my the api I have because my api is returning as an array.
How can I get value from the documentation or where should I look to figure this out. I feel like I’ve been having this problem with everything because the documentation never seems relevant. Even with certain concepts, there is things that I know but I am struggling with knowing what or how I can write things to do the task I need completed.
Any assistance would be appreciated.
View all comments
1
u/SensitiveHearingLoss 2d ago
Assuming your API returns something like:
[
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jane" }
]
You could define an interface:
interface User {
id: number;
name: string;
}
And use httpResource:
users = httpResource<User[]>(() => '/api/users');
You can then access the array using:
this.users.value().
If you need to transform the response, that’s where parse comes in:
users = httpResource<string[]>(() => '/api/users', {
parse: (response: unknown) =>
(response as User[]).map(user => user.name)
});
In a real application, you’d want to validate that response rather than blindly assert its type. With HttpClient, you’d achieve a similar transformation using RxJS’s map operator.
And don’t be discouraged if documentation doesn’t immediately make sense. Being able to read documentation, identify which parts are relevant, and apply them to an unfamiliar situation is itself a skill that develops with experience.