为了账号安全,请及时绑定邮箱和手机立即绑定

API 结果说它是空的,但它不是

API 结果说它是空的,但它不是

慕莱坞森 2023-05-25 16:50:11
我制作了一个 API 来显示用户的关注者和关注用户。一切都在屏幕上正确显示。但问题是,如果我在console.log()调用它说它是一个空数组的方法后尝试存储它的数组。我真的被困住了,不知道该怎么办。这是我的示例,有人可以帮忙或遇到同样的问题请告诉我。使用 OnInit:ngOnInit(): void {    localStorage.setItem("gd", "78F88FC0-7A58-49CD-881E-4B36C5C29B71");    this.getUsers();    this.getFollowing();    this.getFollowers();    console.log("Followers: ", this.followers)    console.log("Following: ", this.following)}方法:getUsers() {    this._userService.getUsers().subscribe(res => {      this.users = res;    })  }  getFollowing() {    this._userService.getFollowing().subscribe(res => {      this.following = res;    })  }  getFollowers() {    this._userService.getFollowers().subscribe(res => {      this.followers = res;    })  }安慰:HTML 输出:
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

我想不那么笼统地回答链接暴露的问题


我们可以使用 forkJoin 进行所有调用并在唯一订阅中获得响应


ngOnInit()

{

    forkJoin(this._userService.getUsers(),

             this._userService.getFollowing(),

             this._userService.getFollowers())

             .subscribe(([users,following,followers])=>{

                   this.users=users

                   this.following=following

                   this.followers=followers

                   console.log(this.users) //<---give value

             })

             console.log(this.users) //<--has no value outside subscribe function

}

是的,只有对订阅功能有意义才能创建 console.log(this.users)


记住:服务返回 observables,我们订阅组件


查看完整回答
反对 回复 2023-05-25
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信