Angular 2可观察到的问题

时间:2016-12-06 08:38:38

标签: javascript angular asynchronous

我正在尝试根据在url

中设置的id获取数据

处理添加模式但收到编辑错误

   export class GradeComponent implements OnInit {

  public isNew:boolean=true;
  public frmGrade: FormGroup;
  public subscription:any;
  public oldGrade:Grade;

  constructor(
    private formBuilder:FormBuilder ,
    private gradeService:GradeService,
    private router:Router,
    private activatedRoute:ActivatedRoute
  ) { }


 ngOnInit() {
    if(typeof this.activatedRoute.snapshot.params['id'] ==='undefined'){
      this.frmGrade = this.formBuilder.group({
        grade: ['', Validators.required],
        description: ''
      });
    }else{
      this.setForUpdate();
    }
  }

  private setForUpdate(){
      this.isNew=false;
      this.gradeService
            .getOneGrade(this.activatedRoute.snapshot.params['id'])
            .subscribe(
                data => { 
                  this.oldGrade = data,
                    this.frmGrade = this.formBuilder.group({
                      grade: [this.oldGrade.grade, Validators.required],
                      description: this.oldGrade.description
                    });
                },
                err => console.error(err),
                () => console.log('done')
              );
  }

但我收到了错误 this.formBuilder未定义如何处理。

2 个答案:

答案 0 :(得分:1)

FormBuilder是一个Injectable服务,只需使用Dependancy Injection获取实例。

在课堂上添加:

constructor(private formBuilder: FormBuilder) {}

你准备好了。

答案 1 :(得分:1)

 export class GradeComponent implements OnInit {

  public isNew:boolean=true;
  public frmGrade: FormGroup;
  public subscription:any;
  public oldGrade:Grade;

  constructor(
    private formBuilder:FormBuilder ,
    private gradeService:GradeService,
    private router:Router,
    private activatedRoute:ActivatedRoute
  ) { }


 ngOnInit() {

   this.frmGrade = this.formBuilder.group({
        grade: ['', Validators.required],
        description: ''
      });

   if(typeof this.activatedRoute.snapshot.params['id'] !=='undefined')  {
    this.setForUpdate();  

    }
  }

  private setForUpdate(){
      this.isNew=false;
      this.gradeService
            .getOneGrade(this.activatedRoute.snapshot.params['id'])
            .subscribe(
                data => { 
                  this.oldGrade = data,
                    this.frmGrade = this.formBuilder.group({
                      grade: [this.oldGrade.grade, Validators.required],
                      description: this.oldGrade.description
                    });
                },
                err => console.error(err),
                () => console.log('done')
              );
  }