-1

I want to set one of the user detail that I am fetching from one of the API call in ngOnInit of my component.

But it is setting it as undefined. Although the API get called.

ngOnInit() {
 sessionStorage.setItem('Key', this.currentUser());
}

currentUser(){
  this.someService.getData().subscribe((res) =>{
    res.body.name
  })
}

I am getting the value undefined in the key when I am trying to access it. I am using angular 6.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Arpan
  • 45
  • 1
  • 8
  • 1
    The GET call is an asynchronous one. Set the value within the subscription block of the currentUser() and from the ngOnInit() just invoke that method. – Nicholas K Mar 12 '20 at 16:24
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Mar 12 '20 at 16:28
  • tried that . That one is not setting value for the first time . – Arpan Mar 12 '20 at 16:31

1 Answers1

1

You're dealing with asyncronous API call that finishes after ngOnInit.

ngOnInit() {
  this.currentUser();
}

currentUser(){
  this.someService.getData().pipe(take(1)).subscribe((res) => {
   sessionStorage.setItem('Key', res.body.name)
  })
}
Andrew Allen
  • 6,512
  • 5
  • 30
  • 73
  • pipe(take(1) ===> what is this for? What it does? take(1). – Arpan Mar 12 '20 at 16:27
  • can normally be skipped off e.g. `this.someService.getData().subscribe(...)` as API calls automatically complete themselves but `take(1)` in case you refactor down the line for multiple outputs from the observable stream. Not unsubscribing is a memory leak. Typical method is a `takeUntil(this.destroyed$)` to prevent subscription running outside component, [See this](https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods) – Andrew Allen Mar 12 '20 at 16:36