为了账号安全,请及时绑定邮箱和手机立即绑定

Angular 9 - 表单组问题

Angular 9 - 表单组问题

jeck猫 2022-11-27 16:09:58
免责声明: 一般来说,我是 Angular 和 TS 的新手。我想要完成的是一个激活组件,如果它在 URL 参数查询中,它要么直接向服务提交代码。如果没有,用户可以将代码插入表单并以这种方式将其提交给服务。当 URL 查询中有代码时该字段被禁用,没有时启用,因此工作正常。我遇到的问题与提交服务有关。我收到以下错误;ERROR TypeError: Cannot read property 'get' of undefined at ActivationComponent.handleActivation (activation.component.ts:48)在第 48 行,我this.validateform.value过去曾导致同样的错误。我已经搞砸了这么长时间,尝试了不同的方法,但我有点迷路了……这是 component.ts:import {Component, Input, Output, EventEmitter, AfterViewInit, OnInit} from '@angular/core';import {ActivatedRoute, Router} from '@angular/router';import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';import {AuthService} from '../auth/auth.service';@Component({  selector: 'app-activation',  templateUrl: './activation.component.html',  styleUrls: ['./activation.component.scss']})export class ActivationComponent implements OnInit {  validateForm!: FormGroup;  showModal = false;  isConfirmLoading = false;  activationCode: string;  error: string;  success: string;  constructor(private router: Router,              private fb: FormBuilder,              private activatedRoute: ActivatedRoute,              private authService: AuthService) {    this.activatedRoute.queryParams.subscribe(params => {      const code = params.code;      if (code){        this.isConfirmLoading = true;        this.handleActivation(code);      }    });  }  ngOnInit() {    this.showModal = true;    this.validateForm = new FormGroup({      CODE: new FormControl({value: this.activationCode, disabled: this.isConfirmLoading}, Validators.required)    });  }  handleActivation(code){    this.error = null;    this.activationCode = code;    if (code === null){      if (!this.validateForm.valid) {        console.log('Invalid Form');        return;      }    }    this.authService.activate(this.validateForm.get('CODE'))      .subscribe(data => {        console.log('SUCCESS!');        console.log(data);      },        error => {        console.log('ERROR!');        console.log(error);        });  }
查看完整描述

1 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

在这里,构造函数中的代码在执行 ngOnInit() 方法之前执行,因此没有初始化表单,您正在尝试使用该表单。


因此,只需更改您的订阅位置,如下所示。这肯定会解决您的问题。


     constructor(private router: Router,

              private fb: FormBuilder,

              private activatedRoute: ActivatedRoute,

              private authService: AuthService) {

   

  }


  ngOnInit() {

    this.showModal = true;

    this.validateForm = new FormGroup({

      CODE: new FormControl({value: this.activationCode, disabled: this.isConfirmLoading}, Validators.required)

    });

 this.activatedRoute.queryParams.subscribe(params => {

      const code = params.code;

      if (code){

        this.isConfirmLoading = true;

        this.handleActivation(code);

      }

    });

  }


查看完整回答
反对 回复 2022-11-27
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信