6

Tôi đang trong quá trình xây dựng một ứng dụng mới yêu cầu tiêu đề ủy quyền. Thông thường tôi sử dụng một cái gì đó rất giống với cách tiếp cận được tìm thấy trong scotch.io article này. Nhưng nó đã đến sự chú ý của tôi rằng HTTP Interceptors bây giờ được hỗ trợ đầy đủ trong hệ sinh thái Angular 4 thông qua HttpClientModule mới và tôi đang cố gắng tìm một số tài liệu về cách sử dụng chúng chính xác.Thiết bị đánh chặn góc 4 góc - Cách sử dụng?

Nếu tôi không chính xác (trong số 4.3) đây là phương pháp hay nhất để tiêm tiêu đề ủy quyền, tôi cũng sẽ mở cho các đề xuất. Tôi nghĩ rằng đó là một tính năng bổ sung gần đây có nghĩa là có thể có lý do chính đáng để chuyển sang phương thức "Được chấp thuận góc cạnh".

+0

http://blog.ninja-squad.com/2017/07/17/http-client-module/ này có vẻ hữu ích – john

+0

Bạn có thể kiểm tra https://github.com/auth0/angular2-jwt /tree/v1.0 1.x nhánh làm ví dụ. – estus

+0

Tài liệu hướng dẫn góc chính thức khá tốt: https://angular.io/guide/http#setting-new-headers – CodeWarrior

Trả lời

6

Câu trả lời này được mượn từ official documentation được liên kết bởi CodeWarrior.

góc cho phép bạn tạo một HttpInterceptor:

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

@Injectable() 
export class NoopInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next.handle(req); 
    } 
} 

mà sau đó bạn có thể tích hợp vào ứng dụng của bạn như sau:

import {NgModule} from '@angular/core'; 
import {HTTP_INTERCEPTORS} from '@angular/common/http'; 

@NgModule({ 
    providers: [{ 
    provide: HTTP_INTERCEPTORS, 
    useClass: NoopInterceptor, 
    multi: true, 
    }], 
}) 
export class AppModule {} 

Để thêm tiêu đề ủy quyền, bạn có thể sao chép các yêu cầu với các tiêu đề đã thay đổi:

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

@Injectable() 
export class AuthInterceptor implements HttpInterceptor { 
    constructor(private auth: AuthService) {} 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    // Get the auth header from the service. 
    const authHeader = this.auth.getAuthorizationHeader(); 
    // Clone the request to add the new header. 
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)}); 
    // Pass on the cloned request instead of the original request. 
    return next.handle(authReq); 
    } 
} 

Lưu ý rằng thiết bị chặn hoạt động như một chai n, vì vậy bạn có thể thiết lập nhiều trình chặn để thực hiện các tác vụ khác nhau.

+0

tại sao bản sao lại là? tại sao không chỉ đặt tiêu đề trực tiếp trong 'req' bằng' rew.headers.set'? – DAG

+2

Dag, theo tài liệu, đối tượng tiêu đề là không thay đổi, vì vậy nếu bạn muốn thay đổi nó, bạn phải sao chép nó. – john

+0

là nó giống nhau trong góc 4.2.3? –

0

Tiêm AuthService đến constructor của Interceptor được đem lại cho tôi lỗi này:

Uncaught Error: Provider parse errors: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./[email protected]:-1

Vì vậy, thay vì tiêm nó vào constructor, tôi sử dụng Injector của @angular/core và nó làm việc tốt. Tôi đang lưu trữ mã thông báo trong localStorage và sử dụng auth cơ bản. Tôi cần phải thiết lập

Authorization: 'Bearer token_string' 

Dưới đây là cách tôi đã thực hiện:

token.interceptor.ts

import {Injectable, Injector} from '@angular/core'; 

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 
import {Observable} from 'rxjs/Observable'; 
import {AuthService} from './auth.service'; 

@Injectable() 
export class TokenInterceptor implements HttpInterceptor { 

    constructor(private injector: Injector) { } 

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 

     const auth = this.injector.get(AuthService); 
     if (auth.getToken()) { 
      request = request.clone({ 
       setHeaders: { 
        Authorization: `Bearer ${auth.getToken()}` 
       } 
      }); 

     } 

     return next.handle(request); 
    } 
} 

getToken chức năng trong AuthService

Tại đây bạn có thể triển khai toàn bộ logic để lấy tiêu đề hoặc chỉ mã thông báo. Ở đây trong trường hợp của tôi, tôi chỉ gọi điều này để lấy chuỗi mã thông báo JWT.

/** 
* Get jwt token 
* @returns {string} 
*/ 
getToken(): string { 
    return localStorage.getItem('token'); 
} 

app.module.ts

nhập các TokenInterceptor

import {TokenInterceptor} from './pathToTheFile/token.interceptor'; 

thêm dòng sau dưới @NgModule trong providers: mảng.

providers: [ 
    { 
     provide: HTTP_INTERCEPTORS, 
     useClass: TokenInterceptor, 
     multi: true 
    } 
    //, other providers 
]