I have an auth service, looking like this:
export class AuthService {
private login$$ : BehaviorSubject<void> = new BehaviorSubject<void>(null);
private logout$$ : BehaviorSubject<void> = new BehaviorSubject<void>(null);
constructor() {
// constructor stuff
}
get login$() : Observable<void> {
return login$$.asObservable();
}
get logout$() : Observable<void> {
return logout$$.asObservable();
}
doLoginStuff() {
// various logic, API calls, etc
// this is probably in a tap() inside some observable's pipe()
this.login$$.next();
}
doLogoutStuff() {
// various logic, API calls, etc
// this is probably in a tap() inside some observable's pipe()
this.logout$$.next();
}
}
Right now, for a component/service to “listen” for login$/logout$, they have to manually subscribe to the observables from AuthService:
export class AnotherService {
constructor(private authService: AuthService) {
this.authService.login$
pipe(
// various operations
)
.subscribe()
// similar block for logout$
}
}
I’m looking to eliminate the boilerplate via a decorator. Something like this:
@DoOnLogin()
onLogin() : void {
// various logic
}
@DoOnLogout()
onLogout() : void {
// various logic
}
The tricky put seems to be accessing/subscribing to the observable inside the Decorator. Angular and Typescript decorators do not seem to be the best of friends.
Has anyone pulled off anything similar?
The application currently runs on Angular 16, if that makes a difference.