typescript 使用从NGRX存储检索的日期填充React性表单

hmae6n7t  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(108)

我想用存储区中的数据填充表单,但无论我尝试什么(setValue、patchValue),表单仍然是空的

export class MyComponent implements OnInit, OnDestroy {
 public newsletterToEdit$: Observable<NewNewsletter> =
    this.store.selectNewsletterToEdit();

 public form = this.fb.group({
    title: ['', Validators.required],
    subtitle: ['', Validators.required],
    message: ['', Validators.required],
    users: [''],
    groups: [''],
    searchedUsers: [''],
    searchedGroups: [''],
    allowReplies: [false, Validators.required],
    replyFrom: ['NONE'],
  });

ngOnInit(): void {

//这个.newMessageForm.控件['标题'].setValue('测试标题');- 〉这是可行的,它用字符串

this.newsletterToEdit$.pipe(
      tap((newsletter) => {
        console.log('newsletter to edit: ', newsletter);

        // this.newMessageForm.patchValue(newsletter) -> another try
        this.form.setValue({
          title: newsletter.title,
          allowReplies: null,
          groups: newsletter.sentToGroupCode[0],
          message: newsletter.message,
          replyFrom: 'NONE',
          searchedGroups: '1',
          searchedUsers: '2',
          subtitle: newsletter.subtitle,
          users: '3',
        });
      })
    );
}
}

我已经检查过了,我确实在存储中有数据,但似乎从未记录控制台日志,因此这意味着未调用管道(tap())

n3ipq98p

n3ipq98p1#

原因是ngrx选择器提供了冷观测值,冷观测值在有人订阅之前不会发出任何数据。
尝试使用

this.newsletterToEdit$.subscribe(
 (newsletter) => {
        console.log('newsletter to edit: ', newsletter);

        // this.newMessageForm.patchValue(newsletter) -> another try
        this.form.setValue({
          title: newsletter.title,
          allowReplies: null,
          groups: newsletter.sentToGroupCode[0],
          message: newsletter.message,
          replyFrom: 'NONE',
          searchedGroups: '1',
          searchedUsers: '2',
          subtitle: newsletter.subtitle,
          users: '3',
        });
      })
});

以便从其接收值。
请注意,您应该取消订阅它或使用声明性方法(例如,将表单定义为可观察的,并使用async管道订阅它)。

相关问题