如何使用或不使用参数来简化http.get

问题描述

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语句不会执行下面的行。

如果没有如下所示的条件,您也可以这样做,

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

希望这可以解决您的问题。干杯!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...