Interceptor not triggered - Angular 7

Asked

Viewed 747 times

1

I created an Interceptor so that it sends the API access token in the request header, but when performing the http call it is not triggered.

Follows the implementations:

auth.interceptor.ts:

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

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

import { environment } from 'src/environments/environment';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AuthInterceptor implements HttpInterceptor {

  private authHeader = 'X-Riot-Token';

  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({ headers: request.headers.set(this.authHeader, environment.api_key) });
    console.log('Antes de fazer a chamado da API', request);
    return next.handle(request).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            console.log('Sucesso: ', event);
          }
        },
        error => {
          if (event instanceof HttpResponse) {
            console.log('Erro: ', error)
          }
        }
      )
    )
  }
}

Appmodule.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import { HttpModule } from '@angular/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthInterceptor } from './shared/interceptors/auth.interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    HttpModule
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
  }],
  bootstrap: [AppComponent]
})
export class AppModule { }

Appcomponent.ts:

import { Component } from '@angular/core';
import { SummonerService } from './shared/services/summoner.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'OP Portrait';

  constructor(private summonerService: SummonerService) { }

  getSummoner() {
    this.summonerService.getByName('Kamikat')
      .subscribe(response => console.log(response));
  }
}

* EDIT *

Summonerservice.ts:

import { Http, Headers } from '@angular/http';
import { environment } from 'src/environments/environment';
import { Injectable } from '@angular/core';
import { Summoner } from '../models/summoner';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';


@Injectable({ providedIn: 'root' })
export class SummonerService {

  private url = environment.endpoint;

  // tslint:disable-next-line: deprecation
  private headers = new Headers({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': 'http://localhost:4200/'
  });

  // tslint:disable-next-line: deprecation
  constructor(private http: Http) { }

  public getByName(summonerName: string): Observable<Summoner> {
    return this.http
      .get(`${this.url}/summoner/v4/summoners/by-name/${summonerName}`, { headers: this.headers })
      .pipe(map(response => new Summoner(response.json())));
  }
}

Could you help me with some clue as to what’s going on?

Att.

  • The log "Before making the API call" is showing or not even that?

  • No, he doesn’t show up.

  • Try taking { providedIn: 'root' } from Injectable

  • Didn’t happen either... :(

  • Edit your question with Summonerservice

  • Tbm declares only Httpclientmodule without Httpmodule

  • Added Summoner Service. Does not work by taking out the Httpmodule statement :(

  • I believe that that answer can help you.

  • So, I had already done this way, first by cloning the original request in a variable, but in my case Angular does not even trigger the Interceptor.

  • People got it, it seems that the problem was related to the HTTP module that I was declaring in appModule. The correct would be Httpclient using both the service and the import in Appmodule. I pulled all the statements from the service’s headers and passed them to the Interceptor and now it’s calling, going through the Interceptor. I’m making a mistake of CORS but I think it should be cross origin problems. Mto thank you all!

Show 5 more comments

1 answer

2


Fabricio seems that the problem is that you are using http instead of http client

First remove Httpmodule from your main module.

And in your service: import { Httpclient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class SummonerService {

  private url = environment.endpoint;


 private httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json', //acho que nao precisa ele adiciona automaticamente por default
     'Access-Control-Allow-Origin': 'http://localhost:4200/'
  })
};


  // tslint:disable-next-line: deprecation
  constructor(private httpClient: HttpClient) { }

  public getByName(summonerName: string): Observable<Summoner> {
    return this.http
      .get<Summoner>(`${this.url}/summoner/v4/summoners/by-name/${summonerName}`, this.httpOptions)

  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.