加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用Observable初始化Reactive Angular2表单?

发布时间:2020-12-17 10:18:13 所属栏目:安全 来源:网络整理
导读:我的计划是将表单的值存储在我的ngrx商店中,以允许我的用户浏览网站并返回表单(如果他们愿意).我们的想法是,表单的值将使用可观察对象从商店重新填充. 这是我目前正在做的事情: constructor(private store: StoreAppState,private fb: FormBuilder) { this.
我的计划是将表单的值存储在我的ngrx商店中,以允许我的用户浏览网站并返回表单(如果他们愿意).我们的想法是,表单的值将使用可观察对象从商店重新填充.

这是我目前正在做的事情:

constructor(private store: Store<AppState>,private fb: FormBuilder) {
    this.images = images;
    this.recipe$= store.select(recipeBuilderSelector);
    this.recipe$.subscribe(recipe => this.recipe = recipe); // console.log() => undefined
    this.recipeForm = fb.group({
      foodName: [this.recipe.name],// also tried with an OR: ( this.recipe.name || '')
      description: [this.recipe.description]
    })
  }

商店给出了一个初始值,我已经看到它正确地通过我的选择器函数,但是当我的表单被创建时,我不认为该值已经返回.因此this.recipe仍未定义.

这是错误的方法,还是我能以某种方式确保在创建表单之前返回observable?

我可以想到两个选择……

选项1:

在显示表单的html上使用*ngIf

<form *ngIf="this.recipe">...</form>

选项2:
在模板中使用async管道并创建模型,如:

零件

model: Observable<FormGroup>;    
...
this.model = store.select(recipeBuilderSelector)
    .startWith(someDefaultValue)
    .map((recipe: Recipe) => {
        return fb.group({
            foodName: [recipe.name],description: [recipe.description]
        })
    })

模板

<app-my-form [model]="(model | async)"></app-my-form>

您必须考虑如何处理商店和当前模型的更新.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读