Problems consuming api rest with angular 5

1

I have this interceptor and I have a service

Interceptor

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent, HttpResponse, HttpUserEvent, HttpHeaders } from '@angular/common/http';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private router : Router){

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {

          if(!req.url.includes('oauth/token') && req.url.includes('pineapple-admin-core')){

              console.log('Si entro');
              let headers : any;

              if(localStorage.getItem('userToken')){
                  console.log(localStorage.getItem('userToken'));
                  headers = new HttpHeaders({
                      'Authorization' : 'Bearer '+ JSON.stringify(localStorage.getItem('userToken')), 
                      'Content-Type' : 'application/json',
                      'Accept' : 'application/json, text/plain, */*' 
                  });
              }
              const cloneReq = req.clone({headers});
              return next.handle(cloneReq);

          }else if(req.url.includes('oauth/token')){
            return next.handle(req.clone());
          }else{
            this.router.navigateByUrl('/login');
          }
    }
}

For the login it works fine, but when I make a request I get to another service

This is my service

getUserMe(){
   return this.http.get(this.getMe).catch(this.handleError);
 } 

I am given a 401 request, in the first request that is the OPTIONS, if I resend the request and put the manual token in the header, the request gives me an answer so I infer that the in the interceptor is not setting the token in the header, which may be happening, that has me crazy, thank you very much for your help

    
asked by Escarlet Escoto del Toro 31.03.2018 в 00:37
source

0 answers