Mudanças entre as edições de "Example of Http Interceptor for login authentication"

De Basef
Ir para: navegação, pesquisa
Linha 1: Linha 1:
 +
Example of Interceptor for login authentication:
  
 +
'''auth-interceptor.js'''
 
<source lang="javascript">
 
<source lang="javascript">
 
import { Injectable, Injector } from '@angular/core';
 
import { Injectable, Injector } from '@angular/core';
Linha 27: Linha 29:
 
}
 
}
 
</source>
 
</source>
 +
 +
'''In your module:'''
 +
<source lang="">
 +
  providers: [
 +
    ...
 +
    {
 +
      provide: HTTP_INTERCEPTORS,
 +
      useClass: AuthInterceptor,
 +
      multi: true
 +
    },
 +
    ...
 +
  ]
 +
</source>
 +
 +
[[Category: AngularJS2]]

Edição das 14h18min de 23 de abril de 2018

Example of Interceptor for login authentication:

auth-interceptor.js

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { LoginService } from './login.service';
 
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
 
  constructor(private injector: Injector) {
 
  }
 
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const loginService = this.injector.get(LoginService);
 
    if (loginService.isLoggedIn()) {
      const authRequest = request.clone(
        { setHeaders:{'Authorization': `Bearer ${loginService.getUser().accessToken}`}});
 
      return next.handle(authRequest);
    } else {
      return next.handle(request);
    }
  }
}

In your module:

Linguagem inválida.

Você precisa especificar uma linguagem, tal como: <source lang="html4strict">...</source>

Linguagens suportadas no realce de sintaxe:

[Expandir]


  providers: [
    ...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    },
    ...
  ]