Angular HttpClient Get method with body

前端 未结 4 1474
一整个雨季
一整个雨季 2020-12-15 16:57

I\'m improving an existing API, and the requirement is to provide a single get method which can accept multiple search criteria and based on those criteria perform the query

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 17:25

    In the service method, you can have your method like below which takes the optional parameters for the search query. And you can send your search parameter over Observe as below.

    getAllSubscribers(
        page?,
        itemsPerPage?,
        userParams?
      ): Observable> {
        const paginatedResult: PaginatedResultSubscribers[]> = new PaginatedResult<
          Subscribers[]
        >();
    
        let params = new HttpParams();
    
        if (page != null && itemsPerPage != null) {
          params = params.append("pageNumber", page);
          params = params.append("pageSize", itemsPerPage);
        }
    
        if (userParams != null) {
          params = params.append("minAge", userParams.minAge);
          params = params.append("maxAge", userParams.maxAge);
            }
    
           return this.http
          .get(this.baseUrl + "/subscribers", { observe: "response", params })
          .pipe(
            map(response => {
              paginatedResult.result = response.body;
              if (response.headers.get("Pagination") != null) {
                paginatedResult.pagination = JSON.parse(
                  response.headers.get("Pagination")
                );
              }
              return paginatedResult;
            })
          );
      }
    

    The basic idea is the use of HttpParams.

提交回复
热议问题