从可观察的角度填充形式 - Angular2

时间:2016-10-29 16:58:01

标签: angular observable angular2-forms angular2-observables

从Angular 2中的observable填充表单的正确方法是什么?

目前我处于半工作状态。当我第一次填充数据时访问表单时,但是当我从表单导航并重新访问页面时,数据就消失了。

组件

export class ProfileEditComponent implements OnInit {
  user: FirebaseObjectObservable<UserProfile>;
  form: FormGroup;
  error = false;
  errorMessage = '';

  constructor(private authService: AuthService, private fb: FormBuilder) { }

  ngOnInit() {
    this.authService.getUserProfile().subscribe(data => {
      this.user = <FirebaseObjectObservable<UserProfile>>data;
      console.log('user', this.user)

      this.user.subscribe( (resp) => {
        this.form.patchValue(
          {
            company: resp.company
          }
        )
      })

    });

    this.form = this.fb.group({
      company: ['', Validators.required],
    });
  }

  onEdit() {
    this.authService.editUserProfile(this.user, this.form.value);
  }
}

模板

  <h2>Profile edit component</h2>
  <a [routerLink]="['/profile']">cancel</a>

  <form [formGroup]="form" (ngSubmit)="onEdit()">
      <div class="form-group">
          <label for="company">Company</label>
          <input 
            formControlName="company" 
            type="company" 
            id="company" 
            #company 
            class="form-control" 
            >
          <span *ngIf="!company.pristine && company.errors != null && company.errors['noCompany']">No Company name</span>
      </div>

      <button type="submit" [disabled]="!form.valid" class="btn btn-primary">Change profile</button>
  </form>

1 个答案:

答案 0 :(得分:2)

我不确定这是否会有所帮助,但是我遇到了类似的问题,我的表单第一次正常加载但是当我浏览应用程序的东西开始破坏时,我不得不将表单初始化代码从ngOnInit移动到监听器关于ActivatedRoute params的变化。有点像这个

export class ProfileEditComponent implements OnInit {
    user: FirebaseObjectObservable<UserProfile>;
    form: FormGroup;
    error = false;
    errorMessage = '';

    constructor(private authService: AuthService, private fb: FormBuilder, private route:ActivatedRoute) { }

    ngOnInit() {
        this.route.params.subscribe(this.onParamsChange.bind(this))
    }

    onParamsChange() {
        this.authService.getUserProfile().subscribe(data => {
            this.user = <FirebaseObjectObservable<UserProfile>>data;
            console.log('user', this.user)

            this.user.subscribe( (resp) => {
                this.form.patchValue(
                    {
                        company: resp.company
                    }
                )
            })

        });

        this.form = this.fb.group({
            company: ['', Validators.required],
        });
    }

    onEdit() {
        this.authService.editUserProfile(this.user, this.form.value);
    }
}