簡體   English   中英

如何使用或不使用參數來簡化 http.get()

[英]How to simplify http.get() with or without params

getPosts(userId?: string): Observable<any> {
  if (userId) {
    const params = new HttpParams().set('userId', userId.toString());
    return this.http.get(ApiUrl + ApiPath, { params }) 
  else {
    return this.http.get(ApiUrl + ApiPath);
  }
}

我正在嘗試組合兩個http.get方法,而不是使用 if 和 else。 基本上,如果定義了 userId,則創建一個查詢參數並將其發送到 API,否則,不要包含該參數。

我試過使用三元運算,但這個運算效果不佳:

this.http.get(ApiUrl + ApiPath, userId ? { params } : null) 

當我在檢查器中檢查 RequestUrl 時,我看到這樣的請求:“api/Post?userId=”

首先,感謝您對重構代碼的興趣。

這可以重構為

  getPosts(userId?: string): Observable<any> {
      if (userId) {
        const params = new HttpParams().set('userId', userId.toString());
        return this.http.get(ApiUrl + ApiPath, { params })
      } 
      return this.http.get(ApiUrl + ApiPath);
    }

您不需要 else 塊,因為 return 語句不執行下面的行。

您也可以在沒有 if 條件的情況下執行此操作,如下所示,

this.http.get(ApiUrl + ApiPath, userId ? { params } : {}) 

希望這可以解決您的問題。 干杯!

暫無
暫無

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

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