]> juplo.de Git - demos/angular/stored-login/commitdiff
fix: `auth.service` reacted inconsistently to `username` changes master
authorKai Moritz <kai@juplo.de>
Tue, 16 Sep 2025 18:51:40 +0000 (20:51 +0200)
committerKai Moritz <kai@juplo.de>
Tue, 16 Sep 2025 19:39:49 +0000 (21:39 +0200)
* 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`.

src/app/app.component.ts
src/app/services/auth.service.ts

index a7422aab3f3ace52be94870152230e9d35e96cc6..f33b4a808c915b1ddf86a1348fa6a293e42e683d 100644 (file)
@@ -12,9 +12,4 @@ export class AppComponent {
   private authService = inject(AuthService);
 
   title = 'stored-login';
   private authService = inject(AuthService);
 
   title = 'stored-login';
-
-  ngOnInit(): void
-  {
-    this.authService.assertUserIsKnown();
-  }
 }
 }
index 26301dbceab883d0e09e2831fd80bcaa52bd62b9..7f89d02209ea0a36991b5828172d4524384b25b1 100644 (file)
@@ -17,9 +17,13 @@ export class AuthService {
   constructor() {
     this.store.select(selectUsername).subscribe(username => {
       this.username = username;
   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<string> {
   }
 
   login(username : string, password : string) : Observable<string> {
@@ -27,13 +31,6 @@ export class AuthService {
     if (shouldFail) {
       return throwError(() => new Error('Simulierter Fehler im Service'));
     }
     if (shouldFail) {
       return throwError(() => new Error('Simulierter Fehler im Service'));
     }
-    this.username = username;
     return of(username).pipe(delay(1000));
   }
     return of(username).pipe(delay(1000));
   }
-
-  assertUserIsKnown(): void {
-    if(!this.username) {
-      this.router.navigate(['login']);
-    }
-  }
 }
 }