2

I am using angular2 http.post in the following service:

import {Injectable, Inject} from 'angular2/core'
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

import 'rxjs/add/operator/map';

//Globals
const URL : string = 'http://myurl.com/listings';

@Injectable()
export class ListingsService {

  //Constructor
  constructor(public http: Http) {}

  postListing(data) {
   this.http.post(URL, data).map(res => res.json())
  }

}

The issue is that I am only allowed to post data as a string inside http.post, where as I need to pass in an Object.

3 Answers 3

5

One way of doing this is using JSON.stringify for making a string of object and then JSON.parse on the server side.

Sign up to request clarification or add additional context in comments.

Comments

1

Probably you need to set Content-Type in your header. You can set default header as follows.

class MyOptions extends RequestOptions {
constructor() {
    super({
        headers: new Headers({
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json'
        })
    });
   }
}

bootstrap(AppComponent, [
   ...,
   provide(RequestOptions, {useClass: MyOptions})
]);

Comments

0

as binariedMe mentioned, JSON.stringify will do what you want. If you want to send binary data maybe you want to look into BSON: https://github.com/mongodb/js-bson

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.