Shay Binyat
Shay Binyat

Reputation: 115

Angular2, HTTP post, send dynamic json

I need to get postKey and postValue from other function that will send the key name and key value, and then post it. but I cannot find a way to send stringify vars and not static value

like this it is not working:

  postRequest(postKey?: any, postValue? any){
    return this._http.post(this._url, JSON.stringify({postKey: PostValue } ))
        .map(res => res.json());
}

only like this is working (static):

  postRequest(post?: any){
        return this._http.post(this._url, JSON.stringify({SomeKey: 'SomeValue' } ))
            .map(res => res.json());
    }

Upvotes: 1

Views: 379

Answers (2)

Shay Binyat
Shay Binyat

Reputation: 115

solved it like this:

 return this._http.post(this._url, '{"' + postKey + '": "' + postValue + '"}')

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

It can be achievable via using ES6 feature

postRequest(postKey?: any, postValue){
   return this._http.post(this._url, postKey ? JSON.stringify({[postKey]: PostValue }: null ))
      .map(res => res.json());
}

Upvotes: 2

Related Questions