繁体   English   中英

使用反应形式从包装在强制对象中的字段发送值

[英]Using Reactive Forms to send value from field wrapped in compulsory object

我正在尝试使用一个信号API将推送通知从角度应用程序发送到移动设备。

标题和内容需要语言的键/值集合。 因此,在表单中,输入字段正在发布字符串,而我收到的错误是:“标题必须是语言代码的键/值集合”。

我尝试为表单控件创建一个对象,然后将输入字段定义为this.title和this.message,但是无法识别表单控件名称。

令人沮丧的是,我可以看到问题出在哪里,但只是不知道正确格式化表单生成器以将正确的值作为潜在对象接受的最佳方法,因此类似:

headings: {
    "en" : ['', Validators.required]
},
content : {
    "en" : ['', Validators.required]
}

//component.ts

ngOnInit() {
    this.logo = environment.logo;
    this.appID = environment.one_signal.app_id;
    this.icon = environment.one_signal.icon;
    this.segments = environment.one_signal.included_segments;

    this.alertForm = this.formBuilder.group({
      app_id: [this.appID],
      included_segments: [[this.segments]],
      small_icon: [this.icon],
      headings: ['', Validators.required],
      content: ['', Validators.required]
    })
}

onSubmit() {
    if (this.alertForm.invalid) {
      return (this.submitting = false) 
    } 
    this.loading = true;

    const formData = this.alertForm.value;

    this.oneSignalService.sendNotification(formData)
    .pipe(first())
    .subscribe(
      () => {
        this.loading = false;
      }
    )
}

//在component.html中形成

<form 
  [formGroup]="alertForm"
  *ngIf="alertForm"
  (ngSubmit)="onSubmit()">
  <label>Title <span>[Required]</span></label>
  <input 
  type="text" 
  hidden 
  formControlName="app_id" 
  id="app_id">
  <input 
  type="text" 
  formControlName="headings" 
  id="headings">
  <label>Message<span>[Required]</span></label>
  <textarea 
  formControlName="content"
  id="content"></textarea>
  <input class="submit" type="submit" value="Send Alert">
</form>

//这节课

export class OneSignal {
    app_id: string;
    included_segments: [string];
    small_icon: string;
    headings: {
        "en": string;
    };
    contents: {
        "en": string
    };
}

有没有人曾经有过使用过一个信号将Web应用程序发布到移动应用程序/设备的经验? 而且,如果是这样,他们如何解决这个问题? 还是您知道以角度为表单构建器格式化键值集合的最佳方法?

您不需要直接从表单发送数据。 您可以从中选择所需的内容,然后再将其发送到sendNotification方法。 例如:let notification = {something1:formData.property1,something2:formData.property2}; this.oneSignalService.sendNotification(notification);

或者您可以定义具有其他属性的打字稿类

暂无
暂无

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

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