【发布时间】:2019-02-06 21:02:21
【问题描述】:
我是 Angular 新手,我正在尝试创建带有多个复选框的新表单屏幕,我有“角色”和“权限”的主表,并且在创建新角色时,用户必须选择权限
我为新角色屏幕创建了一个新表单,还创建了权限服务,但是当使用 map 来创建表单数组时,我得到了上面的错误
import { FormBuilder, FormArray } from '@angular/forms';
import { Injectable, ɵConsole } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Role } from '../model/role.model';
import { Permission } from '../model/permission.model';
import { Observable} from 'rxjs';
import { NewroleComponent } from '../Components/newrole/newrole.component';
import { map } from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { PermissionService } from './permission.service';
@Injectable({
providedIn: 'root'
})
export class RoleService {
private serviceUrl = 'https://adminfinal2.herokuapp.com/rolesonhp';
httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'})};
permissions;
constructor(private http: HttpClient, private permissionService: PermissionService, private formBuilder: FormBuilder ) {
this.permissionService.getPermission().subscribe(results => {
if (!results) {
return;
}
console.log(results);
//this.permissions = new FormArray(results);
console.log(this.permissions);
});
const controls = this.permissions.map(c => new FormControl(false));
controls[0].setValue(true); // Set the first checkbox to true (checked)
this.form = this.formBuilder.group({
permissions: new FormArray(controls)
});
}
form: FormGroup = new FormGroup({
$key: new FormControl(null),
roleName: new FormControl('', Validators.required),
description: new FormControl('',Validators.required),
// permissions: new FormArray([ new FormControl(false)])
});
initializeFormGroup() {
this.form.setValue({
$key: null,
roleName: '',
description: '',
controls:''
});
}
populateForm(role) {
// console.log('in service: ' + user.userName_gmail);
this.form.setValue({
$key: role.roleId,
roleName: role.name,
description: role.description,
});
}
getRole(): Observable<Role[]> {
return this.http.get<Role[]>(this.serviceUrl);
}
addRole(role): Observable<Role> {
return this.http.post<Role>(this.serviceUrl, role, this.httpOptions);
}
}
打印结果时(console.log(results);),我确实在控制台中看到了值。
【问题讨论】:
-
订阅是异步的。假设您从
results设置this.permissions.. 在可观察返回之前不会设置...所以它很可能在外部未定义
标签: angular