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
.