Angular Interceptor 5 is not triggered

Asked

Viewed 868 times

3

Follows my code:

app module.:

import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { CoreModule } from './@core/core.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ThemeModule } from './@theme/theme.module';
import { LoginComponent } from './pages/autenticacao/login.component';
import { AuthService } from './auth/auth.service';
import { TokenInterceptor } from './auth/token.interceptor';


@NgModule({
  declarations: [ AppComponent, LoginComponent ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,

    NgbModule.forRoot(),
    ThemeModule.forRoot(),
    CoreModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [
    AuthService,
    { provide: APP_BASE_HREF, useValue: '/' },
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
  ],
})
export class AppModule {
}

Interceptor:

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

import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';

import { AuthService } from './auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(public auth: AuthService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return fromPromise(this.auth.getToken()).switchMap((token) => {
            const headers = request.headers.set('Authorization', 'Bearer ' + token);
            const requestClone = request.clone({
                headers,
            });
            return next.handle(requestClone);
        });
    }
}

Auth.service:

import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { Router } from '@angular/router';

@Injectable()
export class AuthService {

    constructor(private router: Router) {}

    public setCredentials(dados) {

        let usuario = {empresa : dados.empresa.CODIGO, nome: dados.data[0].NOME, codigo : dados.data[0].CODIGO, grupo : dados.data[0].GRUPO};

        let limberSettings = {
            session: {
                paramsrole      : this.setParametros(usuario),
                breadcrumbs     : [],
                arrayofrolenames: [],
                token           : dados.data[0].TOKEN,
                usuario         : {
                    codigo        : dados.data[0].CODIGO,
                    nome          : dados.data[0].NOME,
                    grupo         : dados.data[0].GRUPO,
                    vendedor      : dados.data[0].VENDEDOR,
                    image         : null,
                },
                empresa         : {
                    codigo        : dados.empresa.CODIGO,
                    nome          : dados.empresa.NOME,
                    logo          : 'assets/images/logo.png',
                },
                estabelecimento : {
                    codigo        : dados.estabelecimento.CODIGO,
                    nome          : dados.estabelecimento.NOME,
                },
                google : {
                    showAuth   : false,
                    showLogout : false,
                },
                datetimelastsession: new Date(),
            },
        };

        localStorage.setItem('limberSettings', JSON.stringify(limberSettings));
        localStorage.setItem('token', JSON.stringify(dados.data[0].TOKEN));
        return true;
    }

    private setParametros(parametros) {

        let params = new URLSearchParams();
        for (let key in parametros) {
            if (parametros.hasOwnProperty(key)) {
                let element = parametros[key];
                params.set(key, element);
            }
        }
        return params;
    }

    public getCredentials() {

        let limberSettings = localStorage.getItem('limberSettings');
        return (limberSettings ? JSON.parse(limberSettings) : undefined);
    }

    public getToken() {

        let token = localStorage.getItem('token');
        return (token ? JSON.parse(token) : undefined);
    }

    public clearCredentials() {
        localStorage.clear();
        this.router.navigate(['./login']);
    }
}

interface Usuario {
    empresa;
    nome;
    codigo;
    grupo;
}

When I make this request what I hope is that the Interceptor triggers taking the token saved in localStorege and adds to the options of the request, the problem is that it does not even trigger.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { API_CONFIG } from '../../../app.setings';

@Injectable()
export class CidadeService {

    constructor(private http: HttpClient) {}

    TodasCidades() {
        let promise = new Promise((resolve, reject) => {
            this.http.get(API_CONFIG.url + 'cidade/all')
            .toPromise().then(
                res => resolve(res),
                error => reject(error),
            );
        });
        return promise;
    }
}

I’m starting with Angular 5 a little while ago, was getting used to Angularjs.

1 answer

3


You cannot modify the body of the request, as it obeys the rule of immutability. From documentation (my translation):

Interceptors exist to examine and change outgoing requests and responses received. However, it may be surprising to know that the classes HttpRequest and HttpResponse are largely immutable. [...] It is invalid to change the body of a request within a Interceptor, but this is not verified by the type system.

In your case, you should remove the line that modifies the original request. Then modify the cloned request:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return fromPromise(this.auth.getToken()).switchMap((token) => {
        const requestClone = request.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });
        return next.handle(requestClone);
    });
}
  • I didn’t know that detail of immutability, now I’ve made it work, thank you.

Browser other questions tagged

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