0

I have build an Angular service which is responsible to retrieve datas from a REST endpoint. It works but I need to know if

  1. There is other ways to do it ?
  2. And even more importantly. If there is, which way is the proper one ?

Thank you for your help.


Here is my code:

@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});
  }
}
Nicolas Dupouy
  • 450
  • 1
  • 7
  • 11
  • Using `httpClient` is going to be your best bet. For Reference: https://angular.io/guide/http –  Apr 28 '20 at 13:54
  • See this this answer... https://stackoverflow.com/questions/45470575/angular-4-httpclient-query-parameters – Adam Dunkerley Apr 28 '20 at 13:56

1 Answers1

0

You can use like this way to call your APIs

  //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'),
      });
  }

I hope it is helpful for you. :)