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

Перехватчик не перехватывает HTTP-запросы (Angular 6)

Я нахожусь в процессе добавления перехватчика к моему угловому проекту. Чтобы звонить на мой API, мне нужно добавить токен-носитель ко всем вызовам. К сожалению, перехватчик, похоже, не называется. Мой код:

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>,
              next: HttpHandler): Observable<HttpEvent<any>> {

        //Retrieve accesstoken from local storage
        const accessToken = localStorage.getItem("access_token");

        //Check if accesToken exists, else send request without bearer token
        if (accessToken) {
            const cloned = req.clone({
                headers: req.headers.set("Authorization",
                    "Bearer " + accessToken)
            });

            console.log('Token added to HTTP request');

            return next.handle(cloned);
        }
        else {
            //No token; proceed request without bearer token
            console.log('No token added to HTTP request');
            return next.handle(req);
        }
    }
}

Кто-нибудь знает, что может вызвать эту проблему? Заранее спасибо.

4b9b3361

Ответ 1

Вы используете правильный способ перехвата.

Для людей, которые используют перехватчик, вам нужно сделать 2 модификации:

Перехватчик в обслуживании

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
  from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    return next.handle(req).do(evt => {
      if (evt instanceof HttpResponse) {
        console.log('---> status:', evt.status);
        console.log('---> filter:', req.params.get('filter'));
      }
    });

  }
}

Предоставить HTTP_INTERCEPTOR

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
(...)
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
  ],

Прочтите эту статью для более подробной информации. Это довольно хорошо

Ответ 2

В моем случае перехватчик не включался в сервисные вызовы, потому что я импортировал HttpClientModule несколько раз для разных модулей.

Позже я обнаружил, что HttpClientModule должен быть импортирован только один раз. Док.

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

Ответ 3

Я сделал то же самое, но здесь не доходит

console.log('---> status:', evt.status);

api.service.ts:

fetchCategories = () =>
ajax.get(this.urlBase + 'categories', { 'Authorization': 'Bearer ' + sessionStorage.token, 'Content-Type': 'application/json' })

category.component.ts

this.apiService.fetchCategories().subscribe({
  next(response) {
    self.categories = response.response
  },
  error(err) {

  }
})

Вызов сделан, но я не могу заставить этот оператор консоли работать.

Любая идея?