213 shaares
3 résultats
taggé
http
Hi hi pour ne pas oublier ce lien !
http.service.ts
import {Injectable} from '@angular/core';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpService extends Http {
constructor (backend: XHRBackend, options: RequestOptions) {
let token = localStorage.getItem('auth_token'); // your custom token getter function here
options.headers.set('Authorization', `Bearer ${token}`);
super(backend, options);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('auth_token');
if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
if (!options) {
// let's make option object
options = {headers: new Headers()};
}
options.headers.set('Authorization', `Bearer ${token}`);
} else {
// we have to add the token to the url object
url.headers.set('Authorization', `Bearer ${token}`);
}
return super.request(url, options).catch(this.catchAuthError(this));
}
private catchAuthError (self: HttpService) {
// we have to pass HttpService's own instance here as `self`
return (res: Response) => {
console.log(res);
if (res.status === 401 || res.status === 403) {
// if not authenticated
console.log(res);
}
return Observable.throw(res);
};
}
}
Certains codes de retour HTTP sont gérés directement par le framework Angular et ne peuvent pas être récupérés au niveau de la requête. C'est notamment le cas pour le code 401, très souvent utilisé puisqu'il informe que l'utilisateur n'est pas loggué en session.
Une manip existante consiste à surcharger le comportement natif du composant HTTP en spécifiant le comportement sur le code erreur de votre choix.
Voici comment rajouter la gestion des codes 401 à une application Angular 4 :
app.module.ts
import { HttpModule, Http } from '@angular/http';
import { AppComponent } from './app.component';
import { AuthenticatedHttpService } from './services/AuthenticatedHttpService';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule
],
providers: [ { provide: Http, useClass: AuthenticatedHttpService } ],
bootstrap: [ AppComponent ]
})
authenticatedHttpService.ts
import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Router, NavigationEnd, Event } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
/**
* This class handles generically the error on authentication (code 401).
*/
@Injectable()
export class AuthenticatedHttpService extends Http {
private router: Router;
constructor(backend: XHRBackend, defaultOptions: RequestOptions, router: Router) {
super(backend, defaultOptions);
this.router = router;
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options).catch((error: Response) => {
if ((error.status === 401 || error.status === 403) && (window.location.href.match(/\?/g) || []).length < 2) {
//DO SOMETHING HERE
//exemple :
if(window.location.href != '/login') {
this.router.navigate(['/login']);
}
}
return Observable.throw("request authentication");
});
}
}