2

从 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>
4

1 回答 1

2

我不确定这是否会有所帮助,但我遇到了类似的问题,我的表单第一次正常加载但是当我在应用程序中导航时事情开始中断,我不得不将表单初始化代码从 ngOnInit 移动到 ActivatedRoute 参数上的侦听器变化。与此类似的东西

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);
    }
}
于 2016-10-29T18:26:52.677 回答