Angle Interceptor 5 does not fire

3

Follow 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 expect is for the interceptor to pick up the token saved in the localStorege and add to the request options, the problem is that it does not even fire.

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, I was getting used to AngularJs.

    
asked by anonymous 15.01.2018 / 11:54

1 answer

3

You can not modify the body of the request, since it obeys the rule of immutability. From the documentation (my translation):

  

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

In your case, you must 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);
    });
}
    
15.01.2018 / 13:09