Vital Verleyen
Vital Verleyen

Reputation: 141

Can not acces array from model in Angular

I've been trying to acces an array from my object. This is my class:

export class Competence {
private _id: string;
private _name: string;
private _isFinished: boolean;
private _subCompetences: string[];


constructor(name: string, isFinished: boolean, subCompetences: string[]) {
    this._name = name;
    this._isFinished = isFinished;
    this._subCompetences = subCompetences;
}

With the getters and setters aswell.

I've been trying to call the subCompetences from a Competence object in this code:

export class StudentModuleDetailsComponent implements OnInit {


private competences: Competence[] = [];
private subcompetences: SubCompetence[] = [];

constructor() { }

ngOnInit() {
   this.getData()
 }
private showSubCompetences(competence: Competence) {
    this.chosenSubCompetences = [];
    console.log(competence.subCompetences)

the showSubCompetences() method gets called with a click event and the clicked competence is given as a parameter.

The competence object is initialized in this method that works perfectly fine.

private getData() {
 this._apiModulesDataService.getModuleById(this._studentDataService.moduleId).subscribe(
  data => {
    this._apiModulesDataService;
    var self = this;
    this.module = data[0];

    this.module.competences.forEach(function (comp) {
      self._apiCompetenceDataService.getCompetenceById(comp).subscribe(
        c => {
          if (!self.competences.includes(c)) {
            self.competences.push(c[0]);
          }
        }
      );
    });
  });
 }
}

Now when I click the competence it only prints out undefined.

And when I only print the competence like so

console.log(competence)

I get this Json as output

{id: "f39356b0-e2a9-11e8-858b-23856324831a", isfinished: null, name: 
 "Knippen", subcompetences: Array(2)}
  id: "f39356b0-e2a9-11e8-858b-23856324831a"
  isfinished: null
  name: "Knippen"
  subcompetences: Array(2)
    0: "08638e20-e2aa-11e8-858b-23856324831a"   
    1: "0d772570-e2aa-11e8-858b-23856324831a"
   length: 2

How do i fix this?

Upvotes: 0

Views: 32

Answers (1)

miselking
miselking

Reputation: 3093

Hmm, first I suggest fixing your model in order to avoid any future errors:

export class Competence {
    private _id: string;
    private _name: string;
    private _isfinished: boolean;
    private _subcompetences: string[];

    constructor(name: string, isFinished: boolean, subCompetences: string[]) {
        this._name = name;
        this._isfinished = isFinished;
        this._subcompetences = subCompetences;
    }

    ...
}

Then, try logging subcompetences like this:

console.log(competence.subcompetences)

Also, with new model you should be able to properly get isfinished property as well...

Hope this helps.

Upvotes: 1

Related Questions