简体   繁体   中英

How to send filters and sort information in Angular2?

I am trying to use PrimeNG datatable and it has some sorting and filtering features. I want to send search/filter data to my restful api but I cannot decide how to do it.

The data is:

{
    "event": {
        "first": 0,
        "rows": 10,
        "sortField": "isDone",
        "sortOrder": 1,
        "filters": {
            "title": {
                "value": "a",
                "matchMode": "startsWith"
            },
            "details": {
                "value": "d",
                "matchMode": "startsWith"
            }
        }
    }
}

The http service doesn't allow to send the data in RequestBody with GET. I think sending the data with http post is against the REST standards. The solution I found is putting the data into url but it is not accepted by my colleagues and they think sending with http post is better.

What is the best practice? How should I send the data? Sending it with http post is acceptable?

In your example you are talking about query/filter parameters. It is fine to send these through a GET request. Generally if you are trying to retrieve resources through a REST API you would use a GET and not a POST.

Of course if the API is one you are building yourself you can opt for a POST too. If you would do that you would create some filter/search endpoint to which you can send a (set of) filter(s). This is often done in the case of more complex searches, in this case you basically make the search/filter a resource too. So you would get an endpoint like this: /event/filter where you could send your POST request with filter

Another option is to add an alias for a common search and still use a GET request. Then endpoint could looke like this instead:

/event/doneEvents?title=a&details=d&top=10

In the end, there is more than one way to solve this, and POST is definitely acceptable for more complex searches. The more important part when building an API is to be consistent, so whatever the choice stick with it for any other complex searches that come up.

However you are not the first person to ask a question like this, and for a more background on this I would like to point you here (stackoverflow) , here (software engineering stackexchange) or here (blog) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM