npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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.