簡體   English   中英

typescript 中的通用 POST、GET - 標頭,響應類型可選

[英]Generic POST, GET in typescript - headers, response type optional

我在 angular 中編寫簡單的應用程序並創建了一些服務,這些服務正在調用 api。

在每項服務更改之前,我都有這樣的方法:

 let addHeaders = new HttpHeaders();
 addHeaders = addHeaders.append('Authorization', apiKey);
 const endpoint = this.BuildAddress(this.MessagesEndp);
 return this.httpClient.post<Array<MessageDto>>(endpoint, dto, {headers: addHeaders});

但是使用 DRY 規則編碼我想為我的所有服務創建一些通用方法,這些服務源自我的“restApiSetvice”。

所以我開始這樣寫:

 Get<T>(endpoint: string, authorization: boolean = true): Observable<T> {
    const apiKey = this.GetApiKey();
    if (authorization) {
      const addHeaders = new HttpHeaders().set('Authorization', apiKey);
      return this.client.get<T>(endpoint, {headers: addHeaders}).pipe(map(result => {
        return result;
      }));
    } else {
      return this.client.get<T>(endpoint).pipe(map(result => {
        return result;
      }));
    }
  }

所以我可以將所有服務中的代碼簡化為:

GetFriendshipRequests(id: number) {
    const endpoint = this.BuildAddress(this.GetFriendshipisRequestsEnd, id);
    return this.Get<Array<number>>(endpoint);
  }

但是有一些問題有些調用不需要授權,所以在例子中我有一些 if 語句

 if (authorization) {

但一些服務也需要發送這個:

 responseType: 'text' as 'json'

根據要求

他們中的一些人還需要發送這個:

observe: 'response'});

(實際上這是小問題,因為我可以隨時觀察所有請求)

但是我如何編寫方法參數來檢索觀察、選項、響應類型等?

如何順利進行

請不要忘記我實際上是在學習 typescript 和 angular,所以請盡可能簡單地寫答案:)

我想要的是:

我只是不想在我的常見 restapiQuery class 中放置多個 if 語句

聽起來像是一個選擇加入/退出的問題。 在您的情況下,在大多數情況下,您希望設置授權 header,而在某些特殊情況下,您希望退出此步驟。

所以我建議你將授權 header 登錄移動到一個攔截器中,它可以處理這個邏輯。 此外,您無需將 HTTP 邏輯包裝在您自己的自定義方法中以處理選擇退出邏輯,您可以簡單地將其移動到實用程序方法中,如下所示:

// authorization-utils.ts
const OPT_OUT_AUTH_HEADER = "X-Opt-Out-Auth";

export function addNoAuthRequired(headers?: HttpHeaders): HttpHeaders{
  headers = headers || new HttpHeaders;
  return headers.set(OPT_OUT_AUTH_HEADER, 'true')
}

export function noAuthRequired(req: HttpRequest<any>): boolean {
  return req.headers.has(OPT_OUT_AUTH_HEADER);
}

// authorization-interceptor.ts
import { noAuthRequired } from './authorization-utils';

@Injectable()
export class AuthorizationInterceptor implementes HttpInterceptor {
  ctor(private readonly authService: AuthorizationService){}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
    return of(req).pipe(
      map(request => noAuthRequired(request)
         ? request
         : request.clone({setHeaders: this.AuthHeaders})
      ),
      mergeMap(request => next.handle(request))
    );
  }

  private get AuthHeaders(){
    return {Authorization: this.authService.GetApiKey()}
  }
}

在應用程序中注冊此攔截器后,授權 header 將添加到所有未退出此步驟的請求中。

要退出它,您需要執行以下操作:

import { addNoAuthRequired } from './authorization-utils';

foo(url:string): Observable<Foo>{
   const headers = addNoAuthRequired();
   return this.http.get<Foo>(url,{headers});
}

這將使重復代碼保持在最低限度,而不會限制 HTTP 操作的靈活性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM