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