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

议会

我尝试使用服务中的数据呈现用于编辑的表单,但出现错误,因为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

因为我不知道如何等待服务中的数据,所以我在InitForm和之间添加了console.log,ngOnOnit而且我start init之前看到了end sub

斯蒂芬·斯沃科塔(Stefan Svrkota)

只需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()">

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何等待渲染组件,直到在Angular 2中收集了所有数据

来自分类Dev

如何在angular2中动态渲染表单输出

来自分类Dev

如何等待Firebase中的数据?

来自分类Dev

在 angular 2 查看之前如何等待数据加载

来自分类Dev

如何等待服务加载数据完成?

来自分类Dev

如何等待服务就绪的Angular?

来自分类Dev

如何等待数据加载到AngularJS中?

来自分类Dev

如何等待来自 API 的数据作为组件中的道具?

来自分类Dev

如何在Angular2中向服务器提交表单?

来自分类Dev

使用元数据在angular2中创建动态表单

来自分类Dev

在Angular2中,如何将不同的数据服务注入到每个组件中

来自分类Dev

如何在Angular2中用数据数组填充表单?

来自分类Dev

如何在angular2的表单数组中显示嵌套数组数据?

来自分类Dev

如何在angular2中发送带有表单数据的帖子

来自分类Dev

如何等待Angular2处理动态多个Http请求?

来自分类Dev

在 Angular 中继续之前如何等待来自服务的新数据

来自分类Dev

如何在Angular2中获取表单

来自分类Dev

来自服务的数据无法在Angular2的OnInit中访问

来自分类Dev

使用Angular2中的服务在组件之间共享数据

来自分类Dev

在Angular中编辑表单

来自分类Dev

如何将数据从服务存储到 angular2 中的类/接口?

来自分类Dev

如何等待Java中的递归承诺

来自分类Dev

如何等待线程在android中完成

来自分类Dev

如何等待jQuery中的动画完成?

来自分类Java

如何等待Java中的进程

来自分类Dev

如何等待R中的按键?

来自分类Dev

如何等待C#中的事件?

来自分类Dev

up:如何等待SPA中的页面?

来自分类Dev

如何等待承诺中的功能?

Related 相关文章

热门标签

归档