0

I would like get token after login.

This is my login.component

login() {
    this.service.login(this.user.value.email, this.user.value.password)
      .then(
        res => console.log(res),
        error => this.handleError(error.error.error)
      );
    // this.router.navigate(['/painel']);
}

And now I have my authentication.ts

    login(email: string, password: string) {
    let promise = new Promise((resolve, reject) => {
      this.http.post<any>(this.api, { email, password })
        .toPromise()
        .then((res) => {

          if(res) {
              this.isAuthenticated = true;
              this.showMenuEmitter.emit(true);
              localStorage.setItem("token", res.token);
              localStorage.setItem("user_id", res.user.id);  
              this.router.navigate(['/painel']);
              resolve(res.token);
             } else {
               this.isAuthenticated = false;
               this.showMenuEmitter.emit(false);
               reject(false);
             }
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    })
    return promise;
  }

And now, I need take the token to work in provider.service

 api: string = `${environment.apiHost}/painel`;
  public headers = new HttpHeaders(
   {
      'Authorization': 'Bearer ' + localStorage.getItem('token')
   }
  );

  constructor(private http: HttpClient) { }

  create(user: any, path: string) {
    return this.http.post(`${this.api}/${path}`, user, { headers: this.headers });
        // toPromise();
  }

But when I logged I get error in console like this:

Http failure response for http://127.0.0.1:8000/api/panel/users: 401 Unauthorized

how to get token in another service after login ?

I can only get token if I take refresh in the page so I get token.

halfer
  • 19,824
  • 17
  • 99
  • 186
Rafael Moura
  • 1,247
  • 2
  • 14
  • 26
  • This answer might help you with your problem: https://stackoverflow.com/a/49830673/6891406 – KShewengger Dec 02 '18 at 23:20
  • I already ready something about interceptor but I dont know to implement its, I new to create a interceptorService.ts for exemple ? – Rafael Moura Dec 02 '18 at 23:47
  • yes you need to create an interceptor service example TokenInterceptorService and inject it on your AppComponent (provide: HTTP_INTERCEPTORS, useClass: TokenInterceptorService, multi: true) and after that whenever you have http calls, it will also pass on this interceptor. – KShewengger Dec 03 '18 at 00:27
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Dec 04 '18 at 08:23

1 Answers1

0

So, I did this way I created a TokenInterceptorService.ts

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

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

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      }
    })
    return next.handle(tokenizedReq)
  }
}

and in my app.module I imported this module http interceptors

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

and my interceptor service too

import { TokenInterceptorService } from './shared/services/token-interceptor/token-interceptor.service';

and finally in providers of app.module added providers: [ ... { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptorService, multi: true } ],

and work perfect, now I can get token after logedd thanks @KShewengger for your help

Rafael Moura
  • 1,247
  • 2
  • 14
  • 26