1

I am working with a reactive form and I am able to append some values from it in order to send an http request make a post. It works when I append text or a file, but I am not sure how to append a date or a boolean or an array.

addPost(postAdded: Post, image: File) {
    const postData = new FormData();
    postData.append("title", postAdded.title); // string
    postAdded.append("startDate", postAdded.startDate); // date
    postAdded.append("private", postAdded.private); // boolean
    postAdded.append("image", image, postAdded.title); // file
    this.http
      .post<{ postId: string }>(
        "http://localhost:3000/api/posts",
        postAdded
      )
      .subscribe(responseData => {
        this.potsUpdated.next([...this.posts]);
        this.router.navigate(["/"]);
      });
  }

The error I get is the following:

Argument of type 'Date' is not assignable to parameter of type 'string | Blob'. Type 'Date' is not assignable to type 'string'.ts(2345)

or

Argument of type 'boolean' is not assignable to parameter of type 'string | Blob'.ts(2345)

and finally the error for array

Argument of type 'string[]' is not assignable to parameter of type 'string | Blob'. Type 'string[]' is not assignable to type 'string'.ts(2345)

When using a boolean

The booleans are for toggles, dates for datepickers.

How could I do it?

2
  • You declare postData, but you're appending to betData. Where is that getting declared? Commented Aug 26, 2019 at 19:09
  • Sorry, that was just a typo Commented Aug 26, 2019 at 19:14

1 Answer 1

3

I think the date should be added in right format. Try this:

var datestr = (new Date(postAdded.startDate)).toUTCString();
formdata.append("start", datestr);

For boolean items:

formdata.append(prop, JSON.stringify(postAdded.private));

For arrays:

for (let i = 0; i < postAdded.participants.length; i ++) {
    formdata.append(prop, JSON.stringify(postAdded.participants[i]));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, I had to mark the solution as not the correct one again because, while it actually works, using stringify I store the information as a string, so in the database is shown as "participants":["[\"MARIO\",\"MARIO\",\"MARIO\"]"] meaning that it does not store anymore the value as an array with several elements, but only as an array with one long string

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.