【问题标题】:Angular2 http observables - how to work with get of undefined?Angular2 http observables - 如何使用未定义的get?
【发布时间】:2018-02-27 21:50:45
【问题描述】:

我尝试使用服务进行验证,但出现如下错误 1:ERROR 错误:formGroup 需要一个 FormGroup 实例。请传一个。

例子:

<div [formGroup]="myGroup">    
  <input formControlName="firstName">    
</div>        

在你的课堂上:

this.myGroup = new FormGroup({    
   firstName: new FormControl()    
});  

2.

ng:///AppModule/HeroFormReactiveComponent.ngfactory.js:95 ERROR TypeError: Cannot read property 'get' of undefined
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective.addControl (vendor.bundle.js:64292)
    at FormControlName.webpackJsonp.../../../forms/@angular/forms.es5.js.FormControlName._setUpControl (vendor.bundle.js:64881)
    at FormControlName.webpackJsonp.../../../forms/@angular/forms.es5.js.FormControlName.ngOnChanges (vendor.bundle.js:64799)
    at checkAndUpdateDirectiveInline (vendor.bundle.js:55512)
    at checkAndUpdateNodeInline (vendor.bundle.js:57011)
    at checkAndUpdateNode (vendor.bundle.js:56950)
    at debugCheckAndUpdateNode (vendor.bundle.js:57811)
    at debugCheckDirectivesFn (vendor.bundle.js:57752)
    at Object.View_HeroFormReactiveComponent_0._co [as updateDirectives] (ng:///AppModule/HeroFormReactiveComponent.ngfactory.js:218)
    at Object.debugUpdateDirectives [as updateDirectives] (vendor.bundle.js:57737)  

我认为我应该使用 observable/callback 函数,以便我们可以在从服务中获取数据后调用 functions()。但我不知道该怎么做......提前谢谢

TS:

export class HeroFormReactiveComponent implements OnInit {
  loginDetailsArray: any;
  detailsArray: any[];
  minLength: any;
  maxLength: any;
  pattern: any;
  // customerDetail: any[];


  hero = {
    username: '',
    password: '',
    email: ''
  };
  constructor(private customerService: CustomerService, private http: Http) {}


  heroForm: FormGroup;


  ngOnInit(): void {

    this.loginDetailsArray = new Object();
    this.detailsArray = new Array();
    this.loadLoginDetails();



  }


  functions() {

    console.log("print");
    console.log(this.loginDetailsArray);

    var minLength = this.loginDetailsArray.rules.username.minlength;
    var maxLength = this.loginDetailsArray.rules.username.maxlength;
    var pattern = this.loginDetailsArray.rules.username.pattern;


    this.heroForm = new FormGroup({

      'username': new FormControl(this.hero.username, [
        Validators.minLength(this.minLength),
        Validators.maxLength(this.maxLength),
        //  Validators.pattern(pattern),
      ]),
      'password': new FormControl(this.hero.password, [
        Validators.minLength(2),
        Validators.maxLength(30),
      ]),
    });
  }

  loadLoginDetails() {

    this.customerService.getLoginDetails().subscribe(res => {

      this.loginDetailsArray = res.json();

      this.functions();

    });
  }




  get username() {
    return this.heroForm.get('username');
  }
  get password() {
    return this.heroForm.get('password');
  }

  save() {

    console.log('Saved: ' + JSON.stringify(this.heroForm.value));


    this.detailsArray.push(this.heroForm.value);


  }
}

服务:

    @Injectable()
export class CustomerService{

    constructor(private http:Http){}


    getLoginDetails(){

        console.log("getLoginDetails")
        //return this.http.get(assets/login.json).map((response: Response) => response.json());
        return this.http.get('assets/login.json').map((response: Response) => response);

    }
}

HTML:

 <div class="container">

    <h1>Login</h1>

    <form (ngSubmit)="save()" [formGroup]="heroForm" #formDir="ngForm">


        <div [hidden]="formDir.submitted">

            <div class="form-group">

                <label for="username">username</label>
                <input id="username" class="form-control" formControlName="username">

                <div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">

                    <div *ngIf="username.errors.required">
                        required
                    </div>
                    <div *ngIf="username.errors.minlength">
                        Please enter a valid email that does not exceed the character limit
                    </div>
                    <div *ngIf="username.errors.maxlength">
                        Please enter a valid email that does not exceed the character limit
                    </div>
                    <div *ngIf="username.errors.pattern">
                        Please enter a valid email address
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label for="password">Password</label>
                <input id="password" class="form-control" formControlName="password" required>

                <div *ngIf="password.invalid && (password.dirty || password.touched)" class="alert alert-danger">

                    <div *ngIf="password.errors.required">
                        required
                    </div>
                    <div *ngIf="password.errors.minlength">
                        Please enter a password with minimum characters
                    </div>
                    <div *ngIf="password.errors.maxlength">
                        Please enter a password that does not exceed 30 characters
                    </div>

                </div>
            </div>



            <button type="submit" class="btn btn-default" [disabled]="heroForm.invalid">Submit</button>
            <!--<td colspan="2">
            <div class="alert alert-danger col-md-12" role="alert" *ngIf="!flag">
              <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> {{errormsg}}
            </div>
          </td>-->


        </div>
    </form>

【问题讨论】:

    标签: angular2-forms angular2-services


    【解决方案1】:

    请查看您要求的工作版本。

    <h1>Login</h1>
    
    <form (ngSubmit)="save()" [formGroup]="heroForm" >
    
    
        <div >
    
            <div class="form-group">
    
                <label for="username">username</label>
                <input #username id="username" class="form-control" formControlName="username">
    
                <div *ngIf="heroForm.get('username').invalid && (heroForm.get('username').dirty || heroForm.get('username').touched)" class="alert alert-danger">
    
    
                    <div *ngIf="heroForm.get('username').hasError('minlength')">
                        Please enter a valid email that does not exceed the character limit
                    </div>
                    <div *ngIf="heroForm.get('username').hasError('maxlength')">
                        Please enter a valid email that does not exceed the character limit
                    </div>
    
                </div>
            </div>
    
            <div class="form-group">
                <label for="password">Password</label>
                <input #password id="password" class="form-control" formControlName="password" required>
    
                <div *ngIf="heroForm.get('password').invalid && (heroForm.get('password').dirty || heroForm.get('password').touched)" class="alert alert-danger">
    
                    <div *ngIf="heroForm.get('password').hasError('required') && heroForm.get('password').touched"
                   class="alert alert-danger"> Password is required.</div>
                    <div *ngIf="heroForm.get('password').hasError('minlength')">
                        Please enter a password with minimum characters
                    </div>
                    <div *ngIf="heroForm.get('password').hasError('maxlength')">
                        Please enter a password that does not exceed 30 characters
                    </div>
    
                </div>
            </div>
    
    
    
            <button type="submit" class="btn btn-default" [disabled]="heroForm.invalid">Submit</button>
            <!--<td colspan="2">
            <div class="alert alert-danger col-md-12" role="alert" *ngIf="!flag">
              <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> {{errormsg}}
            </div>
          </td>-->
    
    
        </div>
    </form>
    

    组件.ts

     export class SampleComponent OnInit { 
    
         public  loginDetailsArray: any= [];
         public detailsArray: any= [];
         public minLength: any;
        public   maxLength: any;
           hero = {
           username: '',
           password: '',
            email: ''
          };
    
    
          constructor( private dataTableService: DataTableService,private fb: 
        FormBuilder    ) {
    
        this.dataTableService = dataTableService;
            this.heroForm = new FormGroup({
    
          'username': new FormControl(this.hero.username),
          'password': new FormControl(this.hero.password, [
            Validators.minLength(2),
            Validators.maxLength(30),
          ]),
        });
    
      }
                    heroForm: FormGroup;
                      public ngOnInit(): void {
    
    
                this. loadLoginDetails();
    
    
               }
    
          loadLoginDetails() {
    
        this.dataTableService.getLoginDetails().subscribe(
          res => {
            this.loginDetailsArray = res;
    
            this. minLength=this.loginDetailsArray.minlength;
            this.maxLength=this.loginDetailsArray.maxLength;
         console.log("minLength",this.minLength);
         this.heroForm.controls["username"].setValidators([
            Validators.minLength(this.minLength),
            Validators.maxLength(this.maxLength)
            //  Validators.pattern(pattern),
          ]);
          console.log(this.heroForm);
    
    
    
          });
      }
            get username() {
            return this.heroForm.get('username');
              }
           get password() {
            return this.heroForm.get('password');
          }
           save() {
    
            console.log('Saved: ' + JSON.stringify(this.heroForm.value));
    
    
            this.detailsArray.push(this.heroForm.value);
    
    
          }
    
    
        }
    

    service.ts

    @Injectable()
    export class DataTableService {
    
        constructor(private http: Http) {
            this.http = http;
        }
    
      getLoginDetails(): Observable<any> {
            return this.http.get('./datatable/data/sample.json').map((response: Response) => response.json());
        }
    }
    

    【讨论】:

    • 我仍然遇到同样的错误。我也收到一个新错误,说 res.json 不是函数以及上面提到的前两个错误
    • loadLoginDetails() { this.customerService.getLoginDetails().subscribe(res => { this.loginDetailsArray = res;//remove res.json this.functions(); }); }
    • 我上面提到的两个错误仍然存​​在。 1. 无法读取未定义的属性获取 2. formGroup 需要一个 FormGroup 实例。请传一个。
    • 检查this.loginDetailsArray是否有值。
    • 如果需要,在订阅函数中添加这个 =true then this.formGroup.controls["username"].setValidators(Validators.required);
    猜你喜欢
    • 2016-04-27
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2016-09-20
    • 2017-07-05
    相关资源
    最近更新 更多