AMarquez94 AMarquez94 - 4 years ago 125
AngularJS Question

Angular 2 - Object properties are return as undefined but they exist

I'm having this problem. I'm working with Angular and calling an API to get an object that has other objects inside. The problem is that I can't access to those objects, as they are returned as undefined. However, logging them in the console (with Google Chrome), the objects are actually there.

These are the relevant fragments of my code:

questionnaire.component.ts

export class QuestionnaireComponent extends BaseComponent {

questionnaires: Models.Survey.Rootobject;
...
ngOnInit() {

...do stuff...

Observable.forkJoin(this.service.getAllQuestionnaires())
.subscribe(res => {

this.questionnaires = res[0];

console.log(this.questionnaires);
console.log(res[0]);
console.log(this.questionnaires.questionnaireItems);

this.numberOfQuestionnaires = this.questionnaires.questionnaireItems.length;

...do more stuff...

});
}
...
}


questionnaire.service.ts

...code...

getAllQuestionnaires() {

return this.http.get<Models.Survey.Rootobject>('/api/v1/xmlquestionnaires').map(res => res[0]);
}


Survey.ts

declare namespace Models.Survey {

...more interfaces...

export interface QuestionnaireItem {
id: string;
name: string;
order: string;
description: string[];
finalText: string[];
questionGroups: QuestionGroup[];
questions: Question[];
toRandomize: string;
}

export interface Rootobject {
questionnaireItems: QuestionnaireItem[];
}

export interface Wrapper {
rootobject: Rootobject;
}

}


And the results of the "console.log(x)" are these:

Resultados logging

QuestionnaireItems is in the object, but accessing directly to it will return undefined.

Do you know what is the problem and how can I solve it?

Thank you very much!

Answer Source

Looks like your method getAllQuestionnaires() is returning a Wrapper object instead of Rootobject.

In such case it would be sufficient to add ".rootobject" to your method EDIT: and fix type, maybe like this:

getAllQuestionnaires() {
    return this.http
        .get<Models.Survey.Wrapper>('/api/v1/xmlquestionnaires')
        .map(res => res[0].rootobject);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download