Подтвердить что ты не робот

Что такое эквивалент httpinterceptor в angular2?

В angularjs у нас есть http-перехватчик

$httpProvider.interceptors.push('myHttpInterceptor');

с помощью которого мы можем подключаться ко всем http-вызовам, а также показывать или скрывать загрузочные столбцы, вести журнал и т.д.

Что эквивалентно в angular2?

4b9b3361

Ответ 1

Как заметил @Günter, нет способа зарегистрировать перехватчики. Вам нужно расширить класс Http и перенести обработку перехвата вокруг HTTP-вызовов

Сначала вы можете создать класс, который расширяет Http:

@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

и зарегистрируйте его, как описано ниже:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

Типы request и requestError могут быть добавлены перед вызовом целевых методов.

Для response one вам нужно подключить некоторую асинхронную обработку в существующую цепочку обработки. Это зависит от ваших потребностей, но вы можете использовать операторов (например, flatMap) Observable.

Наконец, для responseError, вам нужно вызвать оператор catch для целевого вызова. Таким образом, вы будете уведомлены, когда в ответе возникнет ошибка.

Эти ссылки могут помочь вам:

Ответ 2

Обновление

Новый HttpClient модуль, представленный в Angular 4.3.0, поддерживает перехватчики https://github.com/angular/angular/compare/4.3.0-rc.0...4.3.0

feat (общий): новый API HttpClient HttpClient - это эволюция существующий API Angular HTTP, который существует вместе с ним в отдельном пакет, @angular/общий/http. Эта структура обеспечивает кодовые базы могут медленно переноситься в новый API.

Новый API значительно улучшает эргономичность и особенности устаревший API. Частичный список новых функций включает в себя:

  • Типированный, синхронный доступ к телу ответа, включая поддержку типов тела JSON.
  • JSON является предполагаемым дефолтом и больше не нуждается в явном анализе
  • Перехватчики позволяют вставлять логику промежуточного программного обеспечения в конвейер
  • Неизменяемые объекты запроса/ответа
  • События для загрузки и загрузки запросов и ответов
  • Структура проверки после проверки и флеш-тестирования

оригинальный

Angular2 не имеет (пока) перехватчиков. Вместо этого вы можете расширить Http, XHRBackend, BaseRequestOptions или любой из других участвующих классов (по крайней мере, в TypeScript и Dart (не знаю о простой JS).

См. также

Ответ 3

В этом репозитории реализована реализация для службы Http @ angular/core-like: https://github.com/voliva/angular2-interceptors

Вы просто объявляете провайдера этой службы в бутстрапе, добавляя любые перехватчики, которые вам нужны, и будут доступны для всех компонентов.

import { provideInterceptorService } from 'ng2-interceptors';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    MyHttpInterceptor,
    provideInterceptorService([
      MyHttpInterceptor,
      /* Add other interceptors here, like "new ServerURLInterceptor()" or
         just "ServerURLInterceptor" if it has a provider */
    ])
  ],
  bootstrap: [AppComponent]
})

Ответ 4

DEPRICATED SINCE Angular 4.3 (HttpInterCeptors вернулись в 4.3)

Вы можете создать свой собственный HTTP-класс и использовать rxjs Subject Service для повторного использования вашего настраиваемого класса Http и реализации ваших действий в пользовательском классе.

Реализация вашего пользовательского класса Http с помощью "HttpSubjectService", который содержит некоторые объекты rxjs.

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';


import { HttpSubjectService } from './httpSubject.service';


@Injectable()
export class CustomHttp extends Http {
   constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private httpSubjectService: HttpSubjectService) {
       super(backend, defaultOptions);

       //Prevent Ajax Request Caching for Internet Explorer
       defaultOptions.headers.append("Cache-control", "no-cache");
       defaultOptions.headers.append("Cache-control", "no-store");
       defaultOptions.headers.append("Pragma", "no-cache");
       defaultOptions.headers.append("Expires", "0");
   }

   request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
       //request Start;
       this.httpSubjectService.addSpinner();
       return super.request(url, options).map(res => {
           //Successful Response;
           this.httpSubjectService.addNotification(res.json());
           return res;
       })
           .catch((err) => {
               //Error Response.
               this.httpSubjectService.removeSpinner();
               this.httpSubjectService.removeOverlay();

               if (err.status === 400 || err.status === 422) {
                   this.httpSubjectService.addHttp403(err);
                   return Observable.throw(err);
               } else if (err.status === 500) {
                   this.httpSubjectService.addHttp500(err);
                   return Observable.throw(err);
               } else {
                   return Observable.empty();
               }
           })
           .finally(() => {
               //After the request;
               this.httpSubjectService.removeSpinner();
           });
   }
}

Пользовательский модуль для регистрации вашего класса CustomHttp - здесь вы перезаписываете реализацию Http по умолчанию из Angular с помощью собственной реализации CustomHttp.

import { NgModule, ValueProvider } from '@angular/core';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http';

//Custom Http
import { HttpSubjectService } from './httpSubject.service';
import { CustomHttp } from './customHttp';

@NgModule({
    imports: [ ],
    providers: [
        HttpSubjectService,
        {
           provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, httpSubjectService: HttpSubjectService) => {
                return new CustomHttp(backend, defaultOptions, httpSubjectService);
            },
            deps: [XHRBackend, RequestOptions, HttpSubjectService]
        }
    ]
})
export class CustomHttpCoreModule {

    constructor() { }
}

теперь нам нужна реализация HttpSubjectService, где мы можем SubScribe для наших пользователей rxjs, когда они вызываются со следующим оператором.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class HttpSubjectService {
    //https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md
    //In our app.component.ts class we will subscribe to this Subjects
    public notificationSubject = new Subject();
    public http403Subject = new Subject();
    public http500Subject = new Subject();
    public overlaySubject = new Subject();
    public spinnerSubject = new Subject();

    constructor() { }

    //some Example methods we call in our CustomHttp Class
    public addNotification(resultJson: any): void {
        this.notificationSubject.next(resultJson);
    }

    public addHttp403(result: any): void {
        this.http403Subject.next(result);
    }

    public addHttp500(result: any): void {
        this.http500Subject.next(result);
    }

    public removeOverlay(): void {
        this.overlaySubject.next(0);
    }

    public addSpinner(): void {
        this.spinnerSubject.next(1);
    }

    public removeSpinner(): void {
        this.spinnerSubject.next(-1);
    }
}

чтобы вызвать ваши пользовательские Реализации, нам необходимо Подключить к Субъектам, например. "app.component.ts".

import { Component } from '@angular/core';
import { HttpSubjectService } from "../HttpInterception/httpSubject.service";
import { Homeservice } from "../HttpServices/home.service";

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
})
export class AppComponent {
    private locals: AppLocalsModel = new AppLocalsModel();

    constructor(private httpSubjectService : HttpSubjectService, private homeService : Homeservice) {}

    ngOnInit(): void {
        this.notifications();
        this.httpRedirects();
        this.spinner();
        this.overlay();
    }

    public loadServiceData(): void {
        this.homeService.getCurrentUsername()
            .subscribe(result => {
                this.locals.username = result;
            });
    }

    private overlay(): void {
        this.httpSubjectService.overlaySubject.subscribe({
            next: () => {
              console.log("Call Overlay Service");
            }
        });
    }

    private spinner(): void {
        this.httpSubjectService.spinnerSubject.subscribe({
            next: (value: number) => {
              console.log("Call Spinner Service");
            }
        });
    }

    private notifications(): void {
        this.httpSubjectService.notificationSubject.subscribe({
            next: (json: any) => {
                console.log("Call Notification Service");
            }
        });
    }

    private httpRedirects(): void {
        this.httpSubjectService.http500Subject.subscribe({
            next: (error: any) => {
                console.log("Navigate to Error Page");
            }
        });

        this.httpSubjectService.http403Subject.subscribe({
            next: (error: any) => {
                console.log("Navigate to Not Authorized Page");
            }
        });
    }
}


class AppLocalsModel {
    public username : string = "noch nicht abgefragt";
}

SINCE Angular 4.3 вы можете использовать InterCeptors

В Angular 4.3 у вас есть встроенные Interceptors, где вы можете реализовать свои собственные вещи, такие как перенаправление для ошибки сервера 500

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class SxpHttp500Interceptor implements HttpInterceptor {

  constructor(public router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(req).do(evt => { }).catch(err => {
          if (err["status"]) {
              if (err.status === 500) {
                  this.router.navigate(['/serverError', { fehler: JSON.stringify(err) }]);
              }
          }
          return Observable.throw(err);
      });
  }
}

вам необходимо зарегистрировать это в своем основном модуле в массиве поставщиков

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { Router } from '@angular/router';
import { SxpHttp500Interceptor } from "./sxpHttp500.interceptor";
 ....

providers: [
    {
        provide: HTTP_INTERCEPTORS, useFactory: (router: Router) => { return new SxpHttp500Interceptor(router) },
        multi: true,
        deps: [Router]
    }
]

Ответ 5

С выпуском Angular 4.3.1 теперь есть интерфейс под названием HttpInterceptor.

Здесь ссылка на документы: https://angular.io/api/common/http/HttpInterceptor

Здесь пример реализации.


Это будет реализация класса перехватчика.

В основном написано как любая другая услуга:

@Injectable()
export class ExceptionsInterceptor implements HttpInterceptor {
    constructor(
        private logger: Logger,
        private exceptionsService: ExceptionsService,
        private notificationsService: NotificationsService
    ) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request)
            .do((event) => {
                // Do nothing here, manage only errors
            }, (err: HttpErrorResponse) => {
                if (!this.exceptionsService.excludeCodes.includes(err.status)) {
                    if (!(err.status === 400 && err.error['_validations'])) {
                        this.logger.error(err);
                        if (!this.notificationsService.hasNotificationData(err.status)) {
                            this.notificationsService.addNotification({ text: err.message, type: MessageColorType.error, data: err.status, uid: UniqueIdUtility.generateId() });
                        }
                    }
                }
            });
    }
}

Затем, поскольку вы будете рассматривать это как обычный сервис, вы должны добавить эту строку в свои поставщики модулей приложения:

{ provide: HTTP_INTERCEPTORS, useClass: ExceptionsInterceptor, multi: true }

Надеюсь, это поможет.

Ответ 7

Я выпустил перехватчик со следующим модулем node. Мы создали этот модуль для нашей внутренней цели, наконец, мы выпустили в менеджере пакетов npm npm install angular2 -resource-and-ajax-interceptor https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor

Ответ 8

Как отметил @squadwuschel, в настоящее время ведется работа по обеспечению этой функциональности в @ angular/http. Это будет в форме нового API HttpClient.

Подробнее см. https://github.com/angular/angular/pull/17143.

Ответ 9

Попробуйте Covalent from Teradata, они предоставляют множество расширений для Angular и Angular Материал.

Отметьте HTTP часть, он содержит отсутствующий HTTP-перехватчик в Angular и RESTService (аналогично рестатулярному).

Я выполнил аутентификацию токена JWT через Ковалентный HTTP в моем примере. Пожалуйста, проверьте здесь.

https://github.com/hantsy/angular2-material-sample/blob/master/src/app/core/auth-http-interceptor.ts

Прочитайте мои заметки о разработке, Проверять токены на основе токена через IHttpInterceptor.