search

Home  >  Q&A  >  body text

javascript - After angularjs obtains the backend data and assigns it to the member variable, the front console reports an error that the member variable is undefined.

After angularjs obtains the back-end data and assigns it to the member variable, the front console reports an error that the member variable is undefined. The error message is as follows:

EXCEPTION: Error in ./ExerciseDetailComponent class ExerciseDetailComponent - inline template:3:12 caused by: Cannot read property 'name' of undefined

Another error message

ORIGINAL EXCEPTION: Cannot read property 'name' of undefined

code show as below:

import { Component, OnInit } from '@angular/core';

import { Exercise } from './exercise'
import { ExerciseService } from './exercise.service'

@Component({
    selector: 'exercise-detail',
    templateUrl: './exercise-detail.component.html',
})
export class ExerciseDetailComponent implements OnInit {

    exercise: Exercise;

    constructor(private exerciseService: ExerciseService) {}

    getExercise(): void {
        this.exerciseService.getExercise().then(exercise => this.exercise = exercise);
    }

    ngOnInit(): void {
        this.getExercise();
    }
}

Because the error code prompts that the attributes in my exercise are not defined, so I changed the code of the exercise declaration above to the following code, and the data obtained from the background can be assigned to the exercise member variables, and the data displayed in the front desk is also It's not undefined, but the data obtained from the data. Although the problem can be solved using this method, it greatly affects the readability of the code.

exercise: Exercise = {
        id: undefined,
        name: undefined,
        timerDuration: undefined
    };

I want to know what causes this? Theoretically, the data obtained from the background has already opened up memory space, and should be directly assigned to member variables without initializing the member variables.
And another component I wrote based on the official angular2 tutorial only declares member variables and does not initialize them, so that the background data can be obtained.

Please answer

巴扎黑巴扎黑2751 days ago469

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-19 10:11:49

    This error may occur because the exercise 就已经是undefined 了吧,所以才没有name这个属性,才会报错,而不是exercise variable is not assigned a value

    reply
    0
  • Cancelreply