Home > other >  Get observable value in my component variable - Angular 13
Get observable value in my component variable - Angular 13

Time:10-25

Using Angular 13, I have the following observable in my service:

      private _user = new BehaviorSubject<ApplicationUser | null>(null); 
      user$ = this._user.asObservable();

The ApplicationUser model is as follow:

    export interface ApplicationUser {
      userName: string;
      role: string;
    }

I know how to access user$ from the template like:

    <li *ngIf="authService.user$ | async as user ; else login">
                  <a href="#" data-uk-icon="user">{{ user.userName }}</a>              
                </li>

But I would like to manipulate it in my component. I have tried:

    user!: ApplicationUser;
    
      ngOnInit(): void {
    
        this.authService.user$      
          .subscribe((test: ApplicationUser) => {
            this.user = test; 
          });
    }

Also tried

    this.user=this.authService.user$.subscribe();

But it complains that Subscription is missing the following properties (username, role)

Also tried

    this.authService.user$
          .subscribe(test=> this.user = test);

But it complains that Type 'ApplicationUser | null' is not assignable to type 'ApplicationUser'

What should be the correct syntax in my component to get the observable into my user variable?

Thank you

CodePudding user response:

Try to add ! to the subscription emitted value:

this.authService.user$.subscribe((test) => this.user = test!);

  • Related