AMarquez94
AMarquez94

Reputation: 277

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!

Upvotes: 1

Views: 4510

Answers (2)

user5664926
user5664926

Reputation:

its normal returning value is undefined. JS is confused because you want to access array in array if you use it like this problem is going to solve i guess

i index in your case 1 to 3

console.log(this.questionnaries[i].questionnaireItems)

Upvotes: 0

Vilmantas Baranauskas
Vilmantas Baranauskas

Reputation: 6726

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);
}

Upvotes: 1

Related Questions