Home > Software design >  ERROR TypeError: Cannot read properties of undefined afterViewInit in Angular
ERROR TypeError: Cannot read properties of undefined afterViewInit in Angular

Time:06-16

Hello Im working on an Angular project and I have my component which is used to edit code on AceEditor, like this :

  public lesson!: LessonId;
  cssResponse = '';
  aceEditor: any = '';
  idLesson = this.route.snapshot.paramMap.get('lessonsName');
  constructor(
    private aceEditorService: AceEditorService,
    private lessonsService: LessonsService,
    private route: ActivatedRoute
  ) {
    this.getLessons();
  }
  getLessons() {
    this.lessonsService.Lesson(this.idLesson).subscribe((lesson: LessonId) => {
      this.lesson = lesson;
      console.log(this.lesson);
    });
  }

  ngAfterViewInit(): void {
    ace.config.set('fontSize', '16px');
    ace.config.set(
      'basePath',
      'https://unpkg.com/[email protected]/src-noconflict'
    );

    this.aceEditor = ace.edit(this.editor.nativeElement);
    this.aceEditor.setTheme('ace/theme/dracula');
    this.aceEditor.session.setMode('ace/mode/css');
    this.aceEditor.on('change', () => {
      this.cssResponse = this.aceEditor.getValue();
      this.aceEditorService.setCssValues(this.cssResponse);
    });
    this.aceEditor.session.setValue(this.lesson.cssArea);
    this.aceEditor.setOptions({
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: false,
      useSoftTabs: true,
      tabSize: 1,
      cursorStyle: 'smooth',
    });
  }

  ngOnInit(): void {}

And my LessonId interface like :

export interface LessonId {
  id: number;
  title: string;
  content: string;
  htmlArea: string;
  cssArea: string;
}

I've got this error when I want to display the 'CssArea'

ERROR TypeError: Cannot read properties of undefined (reading 'cssArea')
at IdeCssExerciceComponent.ngAfterViewInit (ide-css-exercice.component.ts:48:49)
at callHook (core.mjs:2551:1)
at callHooks (core.mjs:2520:1)
at executeInitAndCheckHooks (core.mjs:2471:1)
at refreshView (core.mjs:9566:1)
at refreshComponent (core.mjs:10692:1)
at refreshChildComponents (core.mjs:9291:1)
at refreshView (core.mjs:9545:1)
at refreshComponent (core.mjs:10692:1)
at refreshChildComponents (core.mjs:9291:1)

I don't know why it it's undefind I tried multiple things and I don't understand why the properties of my services isn't in my interface Anyone can help me ? please

CodePudding user response:

You've set up a race condition: If this.getLessons(); doesn't complete before ngAfterViewInit(), this.lesson will be undefined. Move this.aceEditor.session.setValue(this.lesson.cssArea); to inside of the getLessons() and getLessons() to after this.aceEditor = ace.edit(this.editor.nativeElement);.

  • Related