在angular2中渲染编辑表单。我如何等待服务中的数据?

时间:2016-12-27 19:29:08

标签: angular observable angular2-template angular2-forms angular2-services

我尝试使用服务中的数据呈现表单以进行编辑,因为我在从服务获取数据之前调用了initForm()方法,因此出现错误。我该如何解决?

我的组件

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { ActivatedRoute, Router } from '@angular/router'

import { 
  FormArray, 
  FormControl, 
  Validators, 
  FormGroup,
  FormBuilder
} from '@angular/forms';

import { Company } from './../company';
import { CompanyService } from './../company.service';


@Component({
  selector: 'app-company-edit',
  templateUrl: './company-edit.component.html'
})


export class CompanyEditComponent implements OnInit {
  companyForm: FormGroup;
  private isNew = true;
  private company: Company;
  private companyId: number;
  private subscription: Subscription;

  constructor(private route: ActivatedRoute,
              private companyService: CompanyService,
              private formBuilder: FormBuilder) { }



  ngOnInit() {
    this.subscription = this.route.params.subscribe(
      (params: any) => {
        if (params.hasOwnProperty('id')) {
          this.isNew = false;
          this.companyId = +params['id'];
          this.companyService.getCompany(this.companyId).subscribe((data) => { 
            this.company = data;
            console.log('end sub');
          })

        } else {
          this.isNew = true
          this.company = null;
        }
        this.initForm();
      }
    )
  }

  onSubmit(){

  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }


  private initForm(){
    let companyName = "";

    if (!this.isNew){
      console.log('start init');
      companyName = this.company.name;
    }

    this.companyForm = this.formBuilder.group({
      name: [companyName, Validators.required]
    })
  }

}

我的服务

import { Injectable } from '@angular/core';
import { Angular2TokenService } from 'angular2-token';
import { Company } from './company';
import { Observable } from 'rxjs/Rx';
import { Headers, Http, Response } from '@angular/http';

import "rxjs/Rx"

@Injectable()
export class CompanyService {
  private company: Company;
  private companies: Company[] = [];

  constructor(private tokenService: Angular2TokenService) { }

  getCompanies(){
    return this.tokenService.get('companies').map((response: Response) => response.json())
  }


  getOwnCompanies(){
    return this.tokenService.get('companies/own').map((response: Response) => response.json())
  }

  getCompany(companyId: number){
    return this.tokenService.get('companies/' + companyId).map((response: Response) => response.json())
  }

}

并且有我的表格

<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="companyForm" (ngSubmit)="onSubmit()">
      <div class="row">
        <div class="col-xs-12">
          <button type="submit" class="btn btn-success" [disabled]="!companyForm.valid">Save</button>
          <a class="btn btn-danger" (click)="onCancel()">Cancel</a>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <label for="name">Name</label>
            <input
              type="text"
              id="name"
              class="form-control"
              formControlName="name">
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

我收到了错误

EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property "name" of undefined

TypeError: Cannot read property "name" of undefined at CompanyEditComponent.initForm

因为我不知道如何等待来自服务的数据。我将console.log添加到InitFormngOnOnit。我在start init之前看到end sub

1 个答案:

答案 0 :(得分:3)

获取数据后,只需致电initForm()

ngOnInit() {
    this.subscription = this.route.params.subscribe(
      (params: any) => {
        if (params.hasOwnProperty('id')) {
          this.isNew = false;
          this.companyId = +params['id'];
          this.companyService.getCompany(this.companyId).subscribe((data) => { 
            this.company = data;
            this.initForm(); // moved it here
            console.log('end sub');
          })
        } else {
          this.isNew = true
          this.company = null;
        }
      }
    )}

编辑:

您还需要在表单上使用NgIf指令,以防止在调用initForm()之前呈现表单:

<form *ngIf="companyForm" [formGroup]="companyForm" (ngSubmit)="onSubmit()">