3.0.1 • Published 7 years ago

ng-http v3.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
7 years ago

ng-http

Helper methods for Angular2 HTTP

Usage

Install ng-http

npm i ng-http -S

Define configuration as NgHttpConfig

import { NgHttpConfig, AfterHookFunction, BeforeHookFunction } from 'ng-http';
import { Response, Request } from '@angular/http';

export class NgHttpConfigDetail implements NgHttpConfig  {
  baseUrl: string;
  afterHook: AfterHookFunction;
  errorHook: AfterHookFunction;
  beforeHook: BeforeHookFunction;

  constructor() {
    this.baseUrl = 'http://api.geonames.org';
    this.afterHook = (res: Response) => {
      return res.json().geonames;
    };
    this.beforeHook = (req: Request) => {
      //just logging
      console.log(req);
      return req;
    }
    this.errorHook = (req: Request) => {
      return console.log('Error Occurred')
    };
  }
}

Import NgHttpModule in root NgModule

...
import { NgModule } from '@angular/core';
import { NgHttpModule } from 'ng-http';
import { ngHttpConfig } from './http.config';
...

@NgModule({
  ...
  imports: [
    NgHttpModule
  ],
  ...
  providers: [
      {
        provide: 'ngHttpConfig',
        useClass: NgHttpConfigDetail
      }
    ]
  ...
})

Inject HttpClient in your service/component for usage

...
import { Component } from '@angular/core';
import { HttpClient } from 'ng-http';
...

@Component({
  ...
})
export class FooComponent {
  constructor(
    private httpClient: HttpClient
  ){}
}

Config Interface

  • baseUrl: string
  • beforeHook: BeforeHookFunction
  • afterHook: AfterHookFunction
  • errorHook: AfterHookFunction

API

  • get(url: string, RequestOptionsArgs?): Observable
  • put(url: string, body: string, options? :RequestOptionsArgs): Observable
  • post(url: string, body: string, options? :RequestOptionsArgs): Observable
  • delete(url: string, RequestOptionsArgs?): Observable
  • patch(url: string, body: string, options? :RequestOptionsArgs): Observable

Setup development Environment

Install Peer Dependencies

$ npm i @angular/core @angular/http
$ npm i rxjs zone.js reflect-metadata core-js

Install Dev Dependencies

$ npm i

Popup development Environment

npm run start