Search code examples
angularcurlparse-platformangular2-http

How to cURL in Angular 2?


I am using Parse REST API to fetch some data using Angular2, everything works fine but I need to fetch data with a descending order, back to Parse documentation the following should be done:

curl -X GET \
-H "X-Parse-Application-Id: appID" \
-H "X-Parse-REST-API-Key: keyID" \
-G \
--data-urlencode 'order=-score' \
https://api.parse.com/1/classes/GameScore

I want to simulate that cURL in my Angular2 code, what I need mainly is to implement : data-urlencode

Currently, here is my Angular2 code:

this.http.get('https://example.com/classes/GameScore').subscribe(data => {
    this.res = data.json().results;
});

Solution

  • You should look at URLSearchParams API which will help you to form query string. Before using it do import URLSearchParams from angular2/http

    Code

    import {URLSearchParams} from 'angular2/http'; //do add this line
    
    var search = new URLSearchParams()
    search.set('order', '-score');
    
    this.http.get('https://example.com/classes/GameScore', { search }).subscribe(data => {
        this.res = data.json().results;
    });