Logan Musselman
Logan Musselman

Reputation: 151

http get request returning undefined

I am running in an Ionic/Angular environment I am trying to do a simple get request using HttpClient my code is as follows :

  ngOnInit(){
this.userprovider.getUsers()
  .subscribe(users => this.users = users, 
    errmess => this.userErrMess = <any>errmess);
  console.log(this.users);
 }

my getUsers function looks like this

getUsers(): Observable<User[]> {
return this.http.get<User[]>(baseURL + 'users')
  .do(data => console.log('All: ' + JSON.stringify(data)))
 .catch(this.handleError);

}

my console log looks like this

profile.ts:44 - undefined

user.ts:30 - All: [{"id":0,"featured":true,"username":"Jackie","password":"password","birthday":"Oct 1, 1994","numkids":2,"profileImg":"images/jackie.jpg","description":"Description goes here","pics":[{"image":"/public/images/jackie.jpg","description":"Description goes here","numLikes":24,"numFavs":3,"comments":[{"description":"Description goes here","author":"user1","date":"Today"},{"description":"Description goes here","author":"user1","date":"Today"}]}],"feed":[{"description":"My first update!","numLikes":12,"numFavs":1,"comments":[{"description":"Description goes here","author":"user1","date":"Today"}],"date":"Today"}],"messages":[],"startDate":"Yesterday","numFriends":28,"numMombo":4}]

I know that I am able to retrieve JSON data because I am able to log it to the console. However, it seems that in ngOnInit when I call the getUser function it is returning undefined. I cannot find an answer as to why this is returning undefined?

Upvotes: 2

Views: 4081

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

you need to add the console log inside the subscribe. since javascript is asynchronous, it does not wait until the XHR response. it keeps on executing. that is why console print undefined. Because at that time response is not assign to users variable.

ngOnInit() {
      this.userprovider.getUsers()
          .subscribe((users) => {
                  this.users = users
                  console.log(this.users);
              },
              errmess => this.userErrMess = < any > errmess);
  }

Upvotes: 4

Related Questions