项目作者: danierdev

项目描述 :
🙅‍♂️Angular Http interceptors configure helpers
高级语言: TypeScript
项目地址: git://github.com/danierdev/ngx-http-configure.git
创建时间: 2019-05-31T21:15:32Z
项目社区:https://github.com/danierdev/ngx-http-configure

开源协议:Other

下载


HTTP interceptors / services configure in Angular

Build Status
version
Downloads
license

Ngx HTTP configure is a library for Angular that helps you reconfigure your interceptors in a clear and concise way by extending the HttpClient API

Installation

To install this library, run:

  1. $ npm install ngx-http-configure

Using the library

Import the configure() helper in your injectable service:

The configure function takes the same parameters as the options http request object.

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. // Import the configure helper from lib
  4. import { configure } from 'ngx-http-configure';
  5. @Injectable()
  6. export class PostService {
  7. baseUrl: string = 'https://jsonplaceholder.typicode.com';
  8. constructor(private http: HttpClient) {}
  9. getPosts() {
  10. return this.http.get(`/posts`, configure({
  11. baseUrl: this.baseUrl,
  12. // Use standard http options
  13. params: {
  14. _sort: 'views',
  15. _order: 'asc',
  16. }
  17. }));
  18. }
  19. }

Once your service method is configured, you can use its options in your interceptor:

  1. import { Injectable } from '@angular/core';
  2. import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
  3. import { Observable } from 'rxjs';
  4. import { reconfigure } from 'ngx-http-configure';
  5. /**
  6. * Prefixes all requests not starting with `http[s]` with configure `baseUrl`.
  7. */
  8. @Injectable()
  9. export class ApiPrefixInterceptor implements HttpInterceptor {
  10. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  11. // for multiple interceptors use the optional `selector`
  12. const selector = ['baseUrl'];
  13. const { config: { baseUrl }, request } = reconfigure(req, selector);
  14. if (!/^(http|https):/i.test(request.url) && baseUrl) {
  15. return next.handle(request.clone({ url: `${baseUrl}${request.url}` }));
  16. }
  17. return next.handle(request);
  18. }
  19. }

License

MIT © Danier Rivas