0
votes

I'm building an authentication service and I want to provide the current user to components in the Angular app.

I'm using a subject / observable of type <User | null> because I want to show when the user is not available. E.g. he is not logged in. However, this causes some problems so I can no longer easily access it in components. (Because of null)

So I was wondering how to properly deal with it. I know this problem seems pretty simple and I hope you can provide some tips or best practice as this won't be the last.

AuthService:

// initially null
private readonly _currentUser = new BehaviorSubject<ApiModel.User | null>(null);
public readonly currentUser$ = this._currentUser.asObservable();

Component:

{{user.email | async }} ->

Property 'email' does not exist on type 'Observable<User | null>

User is just an interface. In the component I inject the service and then provide the observable as user.

2

2 Answers

2
votes

Correct syntax should be {{ (user | async)?.email }}.

Maybe you don't need ? if you know the user object is always going to exist when async pipe is used.

-1
votes

I think using the optional chaining operator might work (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) and having the component be {{user?.email | async}}