http get请求返回undefined

时间:2017-12-20 17:40:31

标签: angular ionic-framework

我在Ionic / Angular环境中运行 我正在尝试使用HttpClient做一个简单的get请求 我的代码如下:

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

我的getUsers函数看起来像这样

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

}

我的控制台日志看起来像这样

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}]

我知道我能够检索JSON数据,因为我能够将其记录到控制台。但是,似乎在ngOnInit中,当我调用getUser函数时,它返回undefined。我找不到为什么这个返回undefined的答案?

1 个答案:

答案 0 :(得分:2)

您需要在subscribe内添加控制台日志。由于javascript是异步的,因此它不会等到XHR响应。它继续执行。这就是控制台打印未定义的原因。因为那时响应没有分配给users变量。

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