【问题标题】:In Angular, what is the proper way to send query parameter to a GET endpoint在 Angular 中,将查询参数发送到 GET 端点的正确方法是什么
【发布时间】:2020-08-12 08:45:45
【问题描述】:

我已经构建了一个 Angular 服务,它负责从 REST 端点检索数据。 它有效,但我需要知道是否

  1. 还有其他方法吗?
  2. 更重要的是。如果有,哪种方式是正确的

感谢您的帮助。


这是我的代码:

@Injectable()
export class XXXService {
  private static ENDPOINT = "./api/XXX/YYY/rate";

  constructor(private http: HttpClient) {
  }

  public getRateDatas(): Observable<IRate[]> {
    const httpParams = new HttpParams()
      .set('paramId', 's1')
      .set('paramCode', 'r1')
      .set('paramNumber', '2');
    return this.http.get<IRate[]>(XXXService.ENDPOINT, {params: httpParams});
  }
}

【问题讨论】:

标签: angular rest


【解决方案1】:

您可以使用这种方式调用您的 API

  //in your service
  Call_GetTypeApi(id){
    this._Url = 'your_API_url?id=' +id;
    return (<Observable<IRate[]>>this.getData(this._Url));
  }

 Call_PostTypeApi(jsonData: string) {
    this._Url = "your_API_url";
    return (<Observable<IRate[]>>this.postData(this._Url, jsonData));
  }


 //Common function for get and post method
  getData(_Url: string) {
    return this.http.get(_Url);
  }

  postData(_Url: string, jsonData?: any) {
    return this.http.post(_Url, jsonData,
      {
        headers: new HttpHeaders().set('Content-Type', 'application/json'),
      });
  }

希望对你有帮助。 :)

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2017-03-14
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多