can not read Property 'map' of Undefined

Asked

Viewed 84 times

0

I’m trying to create some dynamic checkboxes, but when I run the browser informs

"ERROR Typeerror: Cannot read Property 'map' of Undefined"

Because?

export class FormPostsComponent implements OnInit {

form: FormGroup;
categories: Category[];

constructor(
    private categoriesService: CategoriesService,
    private formBuilder: FormBuilder
) { }

ngOnInit() {

    this.categoriesService.read().subscribe(categories => this.categories = categories);

    this.form = this.formBuilder.group({
        id: [null],
        title: [null, [Validators.required, Validators.minLength(3)]],
        body: [null, [Validators.required]],
        categories: this.buildCategories(),
        tags: [null],
        imgFeatured: [null],
        slug: [null]
    });
}

buildCategories() {

    const values = this.categories.map(x => new FormControl(false));

    return this.formBuilder.group(values);
}

}

1 answer

1

Squeal like that

ngOnInit() {

this.categoriesService.read().subscribe(categories =>{ 
this.form = this.formBuilder.group({
    id: [null],
    title: [null, [Validators.required, Validators.minLength(3)]],
    body: [null, [Validators.required]],
    categories: this.buildCategories(categories ),
    tags: [null],
    imgFeatured: [null],
    slug: [null]
 });
});

buildCategories(categories) {

 const values = categories.map(x => new FormControl(false));

 return this.formBuilder.group(values);
}

This error is because it only receives the data in the request after calling the method

Browser other questions tagged

You are not signed in. Login or sign up in order to post.