问题描述
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 } : {})
希望这可以解决您的问题。干杯!