慕萊塢森
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,我們訂閱組件
添加回答
舉報
0/150
提交
取消