ค้นหาเว็บไซต์

typescript - วิธีการขยาย HTTP client ของ Angular?


ฉันตระหนักว่ารหัสต่อไปนี้ไม่ใช่ Angular ที่ถูกต้อง อย่างไรก็ตามฉันเพียงแค่ใช้มันเพื่อพยายามแสดงให้เห็นภาพว่า ฉันต้องการทำอะไร

ฉันอยากขยายไคลเอนต์ HTTP ของ Angular เพื่อเพิ่มเฮดเดอร์บางอย่าง

ฉันกำลังจินตนาการในการสร้างคลาสที่ดูเหมือนแบบนี้ ซึ่งฉันขยายคลาส http client ของ Angular จากนั้นในตัวสร้างฉันตั้งค่า header เริ่มต้น:

import { Injectable } from '@angular/core'
import { HttpClient, HttpHandler } from '@angular/common/http'
import { AuthenticationService } from './authentication.service.ts'

@Injectable()
export class AuthenticatedHTTPClient extends HttpClient {
    constructor(
        handler: HttpHandler,
        auth: AuthenticationService
    ){
        super(handler)
        this.headers.set('Authorization', this.auth.accessToken)
    }
}

ตอนนี้เมื่อฉันบริโภคมันกับ, ตัวอย่างเช่น:

constructor(
    authHttp: AuthenticatedHTTPClient
){ }

...

this.authHttp.get('/api/something')

ไคลเอนต์ authHttp ที่ฉันใช้อยู่จะมีการตั้งค่า header แล้ว นี่เป็นไปได้หรือไม่?

คำตอบ #1

Angular มีอินเทอร์เฟซ, HttpInterceptor, ที่จะช่วยให้คุณบรรลุฟังก์ชันที่คุณต้องการในวิธีที่ง่ายขึ้นมาก

คุณสามารถอ่านเพิ่มเติมเกี่ยวกับอินเทอร์เฟซ HttpInterceptor ได้ที่นี่: https://angular.io/api/common/http/HttpInterceptor

คำตอบ #2

ฉันคิดว่าคุณจำเป็นต้องตั้งค่าหัวข้อที่กำหนดเองสำหรับแต่ละวิธี...

อาจจะช่วยคุณได้นะ!

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AppServices {

  public httpHeaders:any;
  public httpGlobalOptions:any;
  public CustomHttpHeader:any;

  constructor(private http:HttpClient) {
    this.httpGlobalOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
      };

  }

  methodCustomHeaders(){
    /* Here you set the Custom Header*/
    this.CustomHttpHeader = { 
        headers: new HttpHeaders(
                        { 'Authorization':  'Bearer ABCDEF', 'Content-Type':'application/json' }
                    ) 
    };

    return this.http.get("/your-path-service/", this.CustomHttpHeader);
  }

  methodGlobalHeader(){
    /*Here you use the Global Header */
     return this.http.get("/your-path-service/", this.httpGlobalOptions);
  }

}