RXJS角存储和修改值
我有一个Angular和RXJS的应用程序,我不明白。我正在尝试从可观察到的值中获取一个值,然后将其修改。
export class FavoritesComponent implements OnInit {
test: any[] = [];
constructor(private userService: UserService) { }
ngOnInit(): void {
this.getUserInfosFav();
console.log(this.test);
this.loadFavoris();
}
getUserInfosFav() {
const idUser = this.userService.decodeToken().id;
return this.userService.getUserInformations(idUser)
.subscribe({
next: (v) => this.test.push(v),
error: (e) => console.error(e),
complete: () => console.info('complete')
})
}
loadFavoris() {
console.log(this.test)
this.test.forEach(val => console.log(val))
在loadfavairis()
中,我只是试图用该值循环测试数组,但是当我尝试循环循环时,然后在控制台中登录时,它没有显示。
这是API调用的价值
[
{
"@context": "/api/contexts/User",
"@id": "/api/users/114",
"@type": "User",
"email": "[email protected]",
"firstname": "tes put ",
"lastname": "test put ",
"favorites": [
{
"@id": "/api/favorites/17",
"@type": "Favorite",
"idSneaker": "367"
},
{
"@id": "/api/favorites/18",
"@type": "Favorite",
"idSneaker": "366"
}
],
"inventories": []
}
]
I have an app in ANGULAR and RXJS I don't understand something. I'm trying to get a value from an observable and modify it afterward.
export class FavoritesComponent implements OnInit {
test: any[] = [];
constructor(private userService: UserService) { }
ngOnInit(): void {
this.getUserInfosFav();
console.log(this.test);
this.loadFavoris();
}
getUserInfosFav() {
const idUser = this.userService.decodeToken().id;
return this.userService.getUserInformations(idUser)
.subscribe({
next: (v) => this.test.push(v),
error: (e) => console.error(e),
complete: () => console.info('complete')
})
}
loadFavoris() {
console.log(this.test)
this.test.forEach(val => console.log(val))
In loadFavoris()
I'm just trying to loop the test array with the value but when I try looping over it and then logging in the console, it shows nothing.
This is the value of the API CALL
[
{
"@context": "/api/contexts/User",
"@id": "/api/users/114",
"@type": "User",
"email": "[email protected]",
"firstname": "tes put ",
"lastname": "test put ",
"favorites": [
{
"@id": "/api/favorites/17",
"@type": "Favorite",
"idSneaker": "367"
},
{
"@id": "/api/favorites/18",
"@type": "Favorite",
"idSneaker": "366"
}
],
"inventories": []
}
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this.userservice.getUserInformations(iduser)
是异步执行的,这意味着在执行以下指令时尚未执行呼叫,并且收到响应的可能性较小。如果要确保获得API返回的值,则必须在
subscribe
中进行。但我想您会获得一个值
也许我正在做很多假设,
this.userService.getUserInformations(idUser)
is executed asynchronously which means the call is not performed yet when the following instruction is executed and the response is less likely to be received.If you want to be sure to get the value the api returns, you have to do it in
subscribe
.Maybe I am making many assumptions but I suppose you will get the value once so you could write your call a bit more simply:
Note also that `subscribe