From: Kai Moritz Date: Tue, 16 Sep 2025 18:51:40 +0000 (+0200) Subject: fix: `auth.service` reacted inconsistently to `username` changes X-Git-Url: https://juplo.de/gitweb/?a=commitdiff_plain;h=0d8083099a09e18e11f625edd0c45fa774e6a313;p=demos%2Fangular%2Fstored-login fix: `auth.service` reacted inconsistently to `username` changes * The subscription for `error` is not required, because the subscription for `username` is also triggered, when the username is reset after an error. * The `login` function must not manipulate the local variable `username` at all. * The separate logic in the app-components's init-hook, that redirects to the login page, when the user is not yet known, is no longer necessary, since the routing can also be triggered in the subscription for `username`. --- diff --git a/src/app/app.component.ts b/src/app/app.component.ts index a7422aa..f33b4a8 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -12,9 +12,4 @@ export class AppComponent { private authService = inject(AuthService); title = 'stored-login'; - - ngOnInit(): void - { - this.authService.assertUserIsKnown(); - } } diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 26301db..7f89d02 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -17,9 +17,13 @@ export class AuthService { constructor() { this.store.select(selectUsername).subscribe(username => { this.username = username; - this.router.navigate(['']); + if (username) { + this.router.navigate(['']); + } + else { + this.router.navigate(['login']); + } }); - this.store.select(selectError).subscribe(error => (this.username = undefined)); } login(username : string, password : string) : Observable { @@ -27,13 +31,6 @@ export class AuthService { if (shouldFail) { return throwError(() => new Error('Simulierter Fehler im Service')); } - this.username = username; return of(username).pipe(delay(1000)); } - - assertUserIsKnown(): void { - if(!this.username) { - this.router.navigate(['login']); - } - } }