Liron Levy
Liron Levy

Reputation: 13

Sending nested objects as a parameter in http.get

I'm trying to send a nested object from my frontend to the backend.
My classes are:

interface ParamsUri {
    iD: number,
    from: string,
    to: string,
    nestedClass: string[]
}

interface Params {
    iD: number,
    from: string,
    to: string,
    nestedClass: NestedClass[]
}

class NestedClass{
    name: string;
    value: string;
}

My http.get command is:

this.http.Get<SomeClass[]>(`api/dashboardfilter`, this.GetParams(paramsUri))

While GetParms is:

private GetParams(params: Parmas): ParamsUri{
        return {
            id: 1,
            from: "temp",
            to: "temp",
            nestedClass: params.nestedClass.map(x => stringify(x))
        }
    }

When console.log(this.GetParams(params).nestedClass, I see what I would expect, i.e., name=XXX&value=YY (one cell of the array). However, when I send the request and follow the query I see that '=' and '&' values were encoded by the get function those the query string is no longer readable to the backend (or at least this is my assumption of why I get null in for those values). I can also confirm that everything other then the nestedclass is received by the backend. I tried other methods to stringify my params (like simple mapping and join) but with no luck.

What am I missing? everywhere I look I find the same answer stringify your nested object, however, this seems to not work as the get function is encoding the stringify string.

Upvotes: 1

Views: 1884

Answers (1)

Insadrian
Insadrian

Reputation: 84

Is there any reason you're not using a POST request when you're sending data to the backend? Generally you wanna use a GET request only to get data from the backend, and a POST request to send data back to your backend.

this.http.Post<SomeClass[]>(`api/dashboardfilter`, YourObject)

Just pass the object to the post request, and it gets included in the body of your post request.

You might need to specifiy the object structure on the backend aswell, depending on your framework.

EDIT: Saw you tagged C#, so im assuming you're using .netcore or similar. In your controller file specify that the request is a post request and that it has your object in the body.

    [HttpPost]
    public IActionResult YourAction([FromBody] YourObject)
    {
        return Ok(SomeService.SomeFunction(YourObject));
    }

Upvotes: 1

Related Questions