0

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": "test@test.com",
        "firstname": "tes put ",
        "lastname": "test put ",
        "favorites": [
            {
                "@id": "/api/favorites/17",
                "@type": "Favorite",
                "idSneaker": "367"
            },
            {
                "@id": "/api/favorites/18",
                "@type": "Favorite",
                "idSneaker": "366"
            }
        ],
        "inventories": []
    }
]
kjod
  • 11
  • 3
  • 2
    Observables subscription runs asynchronously, so the `this.loadFavoris();` call gets executed before the API returns. Also you need to provide the service code and explain a bit more the use case that you are trying to achieve in order to get a better help. – cybering Jul 03 '22 at 22:42

1 Answers1

1

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:

return this.userService.getUserInformations(idUser)
  .subscribe(v => { loadFavoris(); });

Note also that `subscribe

C.Champagne
  • 5,381
  • 2
  • 23
  • 35