> For the complete documentation index, see [llms.txt](https://guide-angular.wishtack.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://guide-angular.wishtack.io/angular/http/utilisation-dans-un-service.md).

# Utilisation dans un Service

{% hint style="success" %}
Le service `HttpClient` ne devrait pas être utilisé directement depuis les composants.

Il faut "wrapper" l'interaction avec les APIs dans des **services dédiés** et **réutilisables**.
{% endhint %}

Il nous faudrait donc un service que l'on puisse utiliser ainsi depuis nos composants :

```typescript
bookRepository.getBookList()
    .subscribe(bookList => this.bookList = bookList);
```

## Transformation de la "response" avec un opérateur

Ce service retourne un `Observable`. La **transformation** des données doit donc se faire **avec un opérateur dans le service**.

{% tabs %}
{% tab title="book-repository.ts" %}

```typescript
@Injectable({
    providedIn: 'root'
})
export class BookRepository {

    private _bookListUrl = 'https://www.googleapis.com/books/v1/volumes?q=extreme%20programming';

    constructor(private _httpClient: HttpClient) {
    }

    getBookList() {
        return this._httpClient.get<GoogleVolumeListResponse>(this._bookListUrl)
            .pipe(map(googleVolumeListResponse => {

                const bookList = googleVolumeListResponse.items
                    .map(item => new Book({
                        title: item.volumeInfo.title
                    }));

                return bookList;

            }));
    }

}
```

{% endtab %}
{% endtabs %}

## Astuce : n'oubliez pas les metadata

Idéalement, pour faciliter l'extensibilité et la gestion de la pagination, pensez à produire un objet englobant la liste ainsi que les "metadata" associées *(pagination etc...)*.

```typescript
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

interface ListResponse<T> {
    meta: {
        totalCount: number
    };
    itemList: T[];
}

class BookRepository {

    getBookList() {
        return this.getBookListWithMeta()
            .pipe(map(bookListResponse => bookListResponse.itemList));
    }

    getBookListWithMeta(): Observable<ListResponse<Book>> {
        return of({
            meta: {
                totalCount: 100
            },
            itemList: [
                new Book(),
                new Book()
            ]
        });
    }

}

new BookRepository().getBookListWithMeta()
    .subscribe(bookListResponse => {
        const bookCount = bookListResponse.meta.totalCount;
        const bookList = bookListResponse.itemList;
    });
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://guide-angular.wishtack.io/angular/http/utilisation-dans-un-service.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
