1

i am unable to assign data to my qMList. console always showing that list is undefined. web service is working and data is coming as observable problem is data not assigning to qMList.

@Injectable()
export class QuestionService {

  public qMList: QuestionMaster[] ;

    constructor(private http: HttpClient) {

    }

    getOsz():Observable<QuestionMaster[]>{

      return this.http.get<QuestionMaster[]>("http://localhost:7073/api/values");

    }

    getQuestions() {

      this.getOsz().subscribe(res => this.qMList = res);

      console.log(this.qMList);

      }
}
3
  • 1
    That's because getOsz is asynchronous, so the log statement is printing before qMList has been set Commented Apr 22, 2018 at 11:39
  • how to avoid this? Commented Apr 22, 2018 at 11:44
  • If you move your console.log into the subscribe, it'll print fine (subscribe(res => { this.qMList = res; console.log(this.qMList);})) Commented Apr 22, 2018 at 11:47

1 Answer 1

1

the problem is int he fact that http request is asyncronious and you should wait for it to fullfil

@Injectable()
export class QuestionService {

  public qMList: QuestionMaster[] ;

    constructor(private http: HttpClient) {

    }

    getOsz():Observable<QuestionMaster[]>{

      return this.http.get<QuestionMaster[]>("http://localhost:7073/api/values");

    }

    getQuestions() {

      this.getOsz().subscribe(res => {
            this.qMList = res;
            console.log(this.qMList);
      });

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

6 Comments

how to do it synchronously?
there is no way to make request syncronious, why would you need it?
i want to use for loop for qMList where i put console.log(this.qMList);.
so make a loop inside of the subscribe section
in the subscribe section how to return qMList to another component.
|

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.