Skip to content

Commit 931f4a7

Browse files
Merge pull request #2479 from lays147/add-http-example
Add http-module use example
2 parents 01dbce9 + a72ef64 commit 931f4a7

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

content/techniques/http-module.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,3 +147,31 @@ export class CatsService {
147147
}
148148
}
149149
```
150+
151+
#### Full example
152+
153+
Since the return value of the `HttpService` methods is an Observable, we can use `rxjs` - `firstValueFrom` or `lastValueFrom` to retrieve the data of the request in the form of a promise.
154+
155+
```typescript
156+
import { catchError, firstValueFrom } from 'rxjs';
157+
158+
@Injectable()
159+
export class CatsService {
160+
private readonly logger = new Logger(CatsService.name);
161+
constructor(private readonly httpService: HttpService) {}
162+
163+
findAll(): Promise<Cat[]> {
164+
const { data } = await firstValueFrom(
165+
this.httpService.get<Cat[]>('http://localhost:3000/cats').pipe(
166+
catchError((error: AxiosError) => {
167+
this.logger.error(error.response.data);
168+
throw 'An error happened!';
169+
}),
170+
),
171+
);
172+
return data;
173+
}
174+
}
175+
```
176+
177+
> info **Hint** Visit RxJS's documentation on [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom) and [`lastValueFrom`](https://rxjs.dev/api/index/function/lastValueFrom) for differences between them.

0 commit comments

Comments
 (0)