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

angular-extended-http-client

v1.0.0

Published

This Angular library allows using HttpClient with strongly-typed callbacks. Easy to use.

Downloads

15

Readme

angular-extended-http-client

Extended HttpClient library

The library allows using Angular's HttpClient with strongly-typed callbacks.

HttpClientExt

The Angular component is an extended HttpClient. It uses HttpClient under the covers.

HttpClientExt exposes HttpClient data via strongly-typed callbacks.

API

  • get
  • post
  • put
  • patch
  • delete

These API are strongly-typed too.

Raison d'être - (n.) a reason for existing

When using Observable with HttpClient, you have to repeat .subscribe(x => ...) all over the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

Due to this, there is tight coupling between the http layer and the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

So, with strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

Strongly-typed callback types

Success

IObservable<T>

This returns the your response model from the body of the underlying HttpClient call.

IObservableHttpResponse

This returns the http response from the underlying HttpClient call.

| Response object | Type | | ---- | ---- | | ok | boolean | | headers | HttpHeaders | | status | number | | statusText | string |

IObservableHttpCustomResponse<T>

This returns the http response with your response model from the underlying HttpClient call.

| Response object | Type | | ---- | ---- | | ok | boolean | | body | T | | headers | HttpHeaders | | status | number | | statusText | string |

Failure

IObservableError<TError>

This returns your error model from the underlying HttpClient call.

This is the custom exception thrown by the API.

It gets this from HttpClient's error.error returned from the API.

IObservableHttpError

This returns the http error from the underlying HttpClient call.

| Error object | Type | | ---- | ---- | | ok | boolean | | message | string | | headers | HttpHeaders | | status | number | | statusText | string |

IObservableHttpCustomError<TError>

This returns the http error with your error model from the underlying HttpClient call.

| Error object | Type | | ---- | ---- | | ok | boolean | | error | TError | | message | string | | headers | HttpHeaders | | status | number | | statusText | string |

Sample Usage

Add the HttpClientExtModule to your app module.

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { HttpHeaders } from '@angular/common/http';

import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        let options = this.addRequestHeaderOptions();        

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure, options);
    }

    private addRequestHeaderOptions() : any {
        var httpHeaders = new HttpHeaders()
                            .set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDc2OTg1MzgsIm5iZiI6MTU0NzY5NDIxOCwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI6InN0cmluZyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6InN0cmluZyIsIkRPQiI6IjEvMTcvMjAxOSIsImlzcyI6InlvdXIgYXBwIiwiYXVkIjoidGhlIGNsaWVudCBvZiB5b3VyIGFwcCJ9.qxFdcdAVKG2Idcsk_tftnkkyB2vsaQx5py1KSMy3fT4");

        let options = {
            headers: httpHeaders,
            retry: 1
        };

        return options;
    }    
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {
    
    this.service.getRaceInfo(response => this.items = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly-typed. Eg. response is type RacingResponse and error is of type APIException.

You only deal with Models in these strongly-typed callbacks.

So, the rest of your code knows only about your Models.

Also, you can still use the traditional route and return Observable from Service API.

    getRaceInfo() : Observable<HttpResponse<RacingResponse>> {
        let url = this.config.apiEndpoint;

        return this.client.get(url)
    }

Implementation details

The HttpClientExt component implements below strongly-typed interface.

export enum ResponseType {
  IObservable,
  IObservableHttpResponse,
  IObservableHttpCustomResponse
}

export enum ErrorType {
  IObservableError,
  IObservableHttpError,
  IObservableHttpCustomError
}

export interface IHttpClientExtended {
  get<TResponse>(url: string, 
                  responseType?: ResponseType,
                  success?: IObservableBase, 
                  failureType?: ErrorType, 
                  failure?: IObservableErrorBase, options?: any, 
                  pipe?: OperatorFunction<HttpResponse<TResponse>, HttpResponse<TResponse>>) : Observable<HttpResponse<TResponse>>;

  post<TRequest, TResponse>(url: string, model: TRequest, 
                              responseType?: ResponseType,
                              success?: IObservableBase, 
                              failureType?: ErrorType,
                              failure?: IObservableErrorBase, options?: any, 
                              pipe?: OperatorFunction<HttpResponse<TResponse>, HttpResponse<TResponse>>) : Observable<HttpResponse<TResponse>>;


  put<T>(url: string, model: T,
            responseType?: ResponseType, 
            success?: IObservableBase,
            failureType?: ErrorType, 
            failure?: IObservableErrorBase, options?: any, 
            pipe?: OperatorFunction<HttpResponse<T>, HttpResponse<T>>) : Observable<HttpResponse<T>>;

  patch<T>(url: string, model: T,
            responseType?: ResponseType, 
            success?: IObservableBase,
            failureType?: ErrorType, 
            failure?: IObservableErrorBase, options?: any, 
            pipe?: OperatorFunction<HttpResponse<T>, HttpResponse<T>>) : Observable<HttpResponse<T>>;            

  delete<TResponse>(url: string,
                      responseType?: ResponseType, 
                      success?: IObservableBase,
                      failureType?: ErrorType, 
                      failure?: IObservableErrorBase, options?: any, 
                      pipe?: OperatorFunction<HttpResponse<TResponse>, HttpResponse<TResponse>>) : Observable<HttpResponse<TResponse>>;
}

You can use underlying HttpClient's .pipe as an optional param.