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

我制作了一个 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;

    })

  }

安慰:

http://img2.mukewang.com/646f215800017af306260318.jpg

HTML 输出:

http://img1.mukewang.com/646f21660001fc6503690806.jpg

慕莱坞森
浏览 61回答 1
1回答

RISEBY

我想不那么笼统地回答链接暴露的问题我们可以使用 forkJoin 进行所有调用并在唯一订阅中获得响应ngOnInit(){&nbsp; &nbsp; forkJoin(this._userService.getUsers(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this._userService.getFollowing(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this._userService.getFollowers())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.subscribe(([users,following,followers])=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.users=users&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.following=following&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.followers=followers&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(this.users) //<---give value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(this.users) //<--has no value outside subscribe function}是的,只有对订阅功能有意义才能创建 console.log(this.users)记住:服务返回 observables,我们订阅组件
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript