@zechtz/fetcher-ng
v1.1.0
Published
The `Fetcher` component is an Angular component that simplifies the process of making HTTP requests and displaying data in your application. It handles loading states, error handling, and data projection through Angular’s content projection feature.
Downloads
1
Readme
Fetcher Component
The Fetcher
component is an Angular component that simplifies the process of making HTTP requests and displaying data in your application. It handles loading states, error handling, and data projection through Angular’s content projection feature.
Table of Contents
Motivation
Building Angular applications often involves making HTTP requests to fetch data from APIs and displaying this data in the UI. While Angular's HttpClient service provides a powerful and flexible way to make HTTP requests, it requires additional boilerplate code to handle common tasks such as:
- Displaying loading indicators while data is being fetched.
- Handling and displaying error messages when requests fail.
- Structuring and projecting the fetched data into the desired UI components.
The Fetcher
component aims to streamline this process by providing a reusable and configurable component that:
- Automatically manages the loading state and displays a customizable loading indicator.
- Simplifies error handling by providing an easy way to catch and display errors.
- Uses Angular's content projection to allow developers to define how the fetched data should be displayed.
This component helps developers save time and effort by reducing repetitive boilerplate code and promoting a consistent approach to data fetching and error handling across the application.
Installation
Install the Fetcher
component via npm:
npm install @zechtz/fetcher-ng
or if you are using yarn
yarn add @zechtz/fetcher-ng
Usage
Basic Usage
To use the Fetcher component, import it into your Angular module and include it in your template. The Fetcher component requires an api URL and optionally accepts query parameters.
import { Component } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { Fetcher } from "@zechtz/fetcher-ng";
@Component({
selector: "app-example",
template: `
<fetcher [api]="'https://api.example.com/data'" [defaultParams]="{ id: 1 }" loadingLabel="Fetching data">
<ng-template let-data>
<div *ngIf="data">
<pre>{{ data | json }}</pre>
</div>
</ng-template>
</fetcher>
`,
imports: [Fetcher, HttpClientModule],
})
export class ExampleComponent {}
Advanced Usage
You can also pass additional query parameters and handle data re-fetching:
@Component({
selector: "app-advanced-example",
template: `
<fetcher [api]="'https://api.example.com/data'" [defaultParams]="{ id: 2 }" loadingLabel="Loading data...">
<ng-template let-data>
<div *ngIf="data">
<pre>{{ data | json }}</pre>
</div>
</ng-template>
</fetcher>
`,
imports: [Fetcher, HttpClientModule],
})
export class AdvancedExampleComponent {
// Method to refetch data with new parameters
refetchData() {
this.fetcher.refetch({ id: 3 });
}
}
Error Handling
Handle errors gracefully by catching them within the Fetcher component:
<fetcher
[api]="'https://api.example.com/data'"
[defaultParams]="{ id: 1 }"
loadingLabel="Loading data..."
>
<ng-template let-data let-error="error">
<div *ngIf="data">
<pre>{{ data | json }}</pre>
</div>
<div *ngIf="error">
<p>Error: {{ error.message }}</p>
</div>
</ng-template>
</fetcher>
Custom Loading Label
Customize the loading label to provide a better user experience:
<fetcher
[api]="'https://api.example.com/data'"
[defaultParams]="{ id: 1 }"
loadingLabel="Please wait, data is loading..."
>
<ng-template let-data>
<div *ngIf="data">
<pre>{{ data | json }}</pre>
</div>
</ng-template>
</fetcher>
Using a Pre-configured HttpClient
If you have a pre-configured HttpClient with a base URL or other settings, you can pass it to the Fetcher component via the httpClient input property.
First, set up your pre-configured HttpClient:
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClient, HttpHandler } from '@angular/common/http';
@Injectable()
export class CustomHttpClient extends HttpClient {
constructor(handler: HttpHandler) {
super(handler);
this.baseUrl = 'https://api.example.com';
}
private baseUrl: string;
get<T>(url: string, options?: any): Observable<T> {
return super.get<T>(this.baseUrl + url, options);
}
}
@NgModule({
imports: [HttpClientModule],
providers: [{ provide: HttpClient, useClass: CustomHttpClient }]
})
export class CustomHttpClientModule {}
Then, pass the custom HttpClient instance to the Fetcher component:
import { Component } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { Fetcher } from '@zechtz/fetcher-ng';
import { CustomHttpClientModule } from './custom-http-client.module';
@Component({
selector: 'app-custom-http-client-example',
template: `
<fetcher
[api]="'/posts'"
[httpClient]="customHttpClient"
loadingLabel="Fetching posts"
>
<ng-template let-response>
<div *ngIf="response; else noData">
<app-autocomplete
label="Select Post"
formControlName="postId"
[displayLabel]="'name'"
(onOptionSelected)="handleOptionSelected($event)"
[options]="response.data"
/>
</div>
<ng-template #noData>No data available</ng-template>
</ng-template>
</fetcher>
`,
imports: [Fetcher, CustomHttpClientModule, HttpClientModule]
})
export class CustomHttpClientExampleComponent {
constructor(public customHttpClient: HttpClient) {}
}
API Reference
Inputs
- api: The API endpoint URL. (required)
- defaultParams: Default query parameters to be sent with the request. (optional)
- loadingLabel: The text to display while loading. (optional)
- httpClient: An optional HttpClient instance to use for making the request. If not provided, the default HttpClient will be used. (optional)
Methods
- refetch(params: { [key: string]: string | number }): Re-fetch data with new parameters.
Examples
Refer to the Storybook documentation for additional examples and usage scenarios.
#Contributing
I welcome contributions! If you would like to contribute, please fork the repository, make your changes, and submit a pull request. For more details, refer to the CONTRIBUTING.md file.
License This project is licensed under the MIT License. See the LICENSE file for details.