Search code examples
angulartypescriptrxjsobservablesubscribe

Angular: Object possibly null after subscribing to it


loadUserInfo() is returning an Observable of type UserModel. I want this.user to be accessible in other functions as well. Right now if I try to access it outside of the subscription it says that it is null. Same with trying to access it in the HTML

  ngOnInit(){
     this.subscriptions.add(this.loadUserInfo().subscribe((user: UserModel) => {
           this.user = user;
      }));
  }
  someOtherFunc(){
     console.log(this.user) //Does not work here
  }

Solution

  • Since the Observable/subscribe operation is asynchronous, you can only access this.user only after the async operation is completed. I have added the this.someOtherFunc() function call in the code below.

     ngOnInit(){
         this.subscriptions.add(this.loadUserInfo().subscribe((user: UserModel) => {
               this.user = user;
               this.someOtherFunc(); // call function here
          }));
      }
      someOtherFunc(){
         console.log(this.user) 
      }
    

    Please see this section of the webpage: https://angular.io/tutorial/toh-pt4#observable-heroservice. Also see this answer: https://stackoverflow.com/a/61754447/3389828