简体   繁体   English

反应形式-在Angular中追加值

[英]Reactive Forms - Appending Values in Angular

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. 我正在使用响应式表单,并且能够从中添加一些值,以便发送http请求进行发布。 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) 无法将类型“日期”分配给类型“字符串”。ts(2345)

or 要么

Argument of type 'boolean' is not assignable to parameter of type 'string | 类型'boolean'的参数不能分配给'string |类型的参数。 Blob'.ts(2345) Blob'.ts(2345)

and finally the error for array 最后是数组的错误

Argument of type 'string[]' is not assignable to parameter of type 'string | 类型'string []'的参数不能分配给类型'string |的参数。 Blob'. 斑点”。 Type 'string[]' is not assignable to type 'string'.ts(2345) 类型“字符串[]”不能分配给类型“字符串”。ts(2345)

When using a boolean 使用布尔值时

The booleans are for toggles, dates for datepickers. 布尔值用于切换,日期用于日期选择器。

How could I do it? 我该怎么办?

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]));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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