2

I want to get 10 questions by Id using loop. But I get error: (TS) Type 'Subscription' is missing the following properties from type 'Question': QuestionId, Content, TestId, Test

My Question class

import { Test } from './test';

export class Question {
    QuestionId: number;
    Content: string;
    TestId: number;
    Test: Test;
}

My get method in data.service

    getQuestionById(id: number) {
        return this.http.get(this.questionUrl + `/${id}`);
    }

My Component

    questions: Question[];
    question: Question;

    getQuestions() {
        for (let i = 1; i < 11; i++) {
            this.questions[i] =
                this.dataService.getQuestionById(i)
                    .subscribe((data1: Question) => {
                        this.question = data1;
                    });
            //this.questions.push(this.dataService.getQuestionById(1)
            //    .subscribe((data1: Question) => {
            //        this.question = data1;
            //    }););
        }
    }

How should I change my getQuestions() method to make it works?

2
  • Where are this.questions and this.question declared? Commented Apr 22, 2020 at 18:36
  • In Component class, I will edit my post in a minute and add them. Commented Apr 22, 2020 at 18:39

1 Answer 1

4

You need to initialize this.questions before for statement.

this.questions = []

I believe that your for statement also needs tweaking

for (let i = 0; i < 11; i++) {
    this.dataService.getQuestionById(i)
        .subscribe((data1: Question) => {
            this.questions.push(data1)
        });
}

It seems that you don't need this.question instance.

Angular uses RxJs (which has subscription mechanism for async calls). You need to push data inside .subscribe function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.