How to pass token with angular 5 and httpclient?

0

I need to pass the token that comes to me from the database so that laravel lets me enter the content. Here I leave my code

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {SessionStorageService} from 'ngx-webstorage';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';

public sesion = false;

user: any = <any>{};



constructor(public _http:HttpClient, 
public _local:SessionStorageService,
public _rutas:Router
) { 

}

 login(a:NgForm){



 const url = 'http://localhost/api/public/login';

this._http.post(url,{
'username':this.user.username,
'password':this.user.password

}).subscribe(data => {

        this.user = data;
        this.sesion = true;
    this._local.store('user',data);
    this._rutas.navigate(['main']);

  console.log('ha ido bien');
  console.log(data);

  }, error => {

 console.log('error');
this.sesion = false;
 });

 }

This function returns the user with the data that happened to him from the html

    
asked by ortiga 28.02.2018 в 12:02
source

1 answer

1

The best solution is to implement Http Interceptors and automatically add the headers needed in this case add the Token to the header.

Here is an example of an implementation that I have:

token.interceptor.ts

import { AuthService } from './auth.service';
import { AuthSessionService } from './auth-session.service';
import { Injectable } from '@angular/core';
import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
    HttpResponse,
    HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { Router } from '@angular/router';



@Injectable()
export class TokenInterceptor {
    constructor(
        private router: Router,
        private authSession: AuthSessionService,
        private auth: AuthService
    ) {}


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authRequest = request.clone({headers: request.headers.set('Authorization', 'JWT ${this.authSession.token}')});
        return next.handle(authRequest).do((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                // do stuff with response if you want
            }
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                if (err.status === 401 || err.status === 403) {
                    this.auth.logout();
                }
            }
        });
    }
}

in the module

import { AuthGuard } from './auth/auth.guard';
import { AuthService } from './auth/auth.service';
import { BrowserModule } from '@angular/platform-browser';
import { AuthSessionService } from './auth/auth-session.service';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './auth/token.interceptor';



@NgModule({
    imports: [
        CommonModule,
        BrowserModule,
        HttpClientModule
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: TokenInterceptor,
            multi: true
        },
        AuthSessionService,
        AuthService,
        AuthGuard
    ]
})
export class ServiciosModule { }
    
answered by 28.02.2018 / 13:53
source