您好我正在进行多重表单验证,我感到非常恐怖 'TypeError:无法读取未定义'
的'forEach'属性我不知道该怎么办。 这是我的
app.component.ts
import { Component } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { FormGroup, FormControl, FormBuilder, Validators, FormArray } from '@angular/forms';
import 'rxjs/add/operator/count';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public employees: FirebaseListObservable<any>;
public updateForm: FormGroup;
public formArray = new FormArray([]);
employeesCount: number;
angular: any;
constructor(af: AngularFire) {
this.employees = af.database.list('/employees');
}
addEmployee( firstname: string, lastname:string, age:number , sex: string) {
this.employees.push({ firstname: firstname, lastname: lastname, age: age, sex:sex});
}
updateEmployee(key: string, firstname: string, lastname:string, age:number , sex: string) {
this.employees.update(key, { firstname: firstname, lastname: lastname, age: age, sex:sex } );
}
deleteEmployee(key: string) {
this.employees.remove(key);
}
ngOnInit() {
this.angular.forEach(this.employees, function(value, key) {
this.formArray.push(
new FormGroup({firstname: new FormControl([Validators.required])})
);
console.log(value);
});
this.updateForm = new FormGroup(
{firstname: new FormControl([Validators.required])}
);
}
}
上述问题由this.employees.forEach(function(employee){...})
我在与 Unhandled Promise rejection: Cannot read property 'arr' of undefined ; Zone: <root> ; Task: WebSocket.addEventListener:message ; Value: TypeError: Cannot read property 'arr' of undefined(…) TypeError: Cannot read property 'arr' of undefined
我努力工作有多难我不知道为什么?
export class AppComponent {
public employees: FirebaseListObservable<any>;
public updateForm: FormGroup;
public arr = new FormArray([]);
constructor(af: AngularFire) {
this.employees = af.database.list('/employees');
}
addEmployee( firstname: string, lastname:string, age:number , sex: string) {
this.employees.push({ firstname: firstname, lastname: lastname, age: age, sex:sex});
}
updateEmployee(key: string, firstname: string, lastname:string, age:number , sex: string) {
this.employees.update(key, { firstname: firstname, lastname: lastname, age: age, sex:sex } );
}
deleteEmployee(key: string) {
this.employees.remove(key);
}
ngOnInit() {
this.employees.forEach(function(e) {
this.arr.push(new FormGroup({firstname: new FormControl([Validators.required])}));
console.log(this.arr);
});
}
答案 0 :(得分:0)
它像你从未为你的angular属性赋值,并确保angular属性值应该是数组。我认为对象不起作用
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach][1]
答案 1 :(得分:0)
您只需致电this.employees.forEach()
即可。您似乎正在尝试使用AngularJS(版本1)方法angular.forEach()
,这在Angular 2中是不必要的。
字段angular
可以删除,因为它不用于任何内容。