]> juplo.de Git - demos/angular/stored-login/commitdiff
redirect to home on successful login
authorKai Moritz <kai@juplo.de>
Mon, 15 Sep 2025 20:01:29 +0000 (22:01 +0200)
committerKai Moritz <kai@juplo.de>
Mon, 15 Sep 2025 20:45:44 +0000 (22:45 +0200)
src/app/login/login.component.html
src/app/login/login.component.ts
src/app/services/auth.service.ts

index 6ca848ad37f521c4fb092594d1b00248e027075e..948fb29c977d01d73af44bed414ee5ff37a05e9e 100644 (file)
@@ -12,4 +12,3 @@
   <button type="submit" [disabled]="isLoading || form.invalid">Login</button>
 </form>
 <div *ngIf="error">{{ error }}</div>
-<div *ngIf="token">Welcome, {{ form.value.username }}! Your token is {{ token }}</div>
index 8de7ea8066cd085bcdb6edcb9ce06b8f6c9d36b2..bbaf374b1ca32bab1a731828822240be12af1b03 100644 (file)
@@ -3,7 +3,7 @@ import { CommonModule } from '@angular/common';
 import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
 import { Store } from '@ngrx/store';
 import { login } from '../store/login.actions';
-import { selectError, selectIsLoading, selectToken } from '../store/login.selectors';
+import { selectError, selectIsLoading } from '../store/login.selectors';
 
 @Component({
   selector: 'app-login',
@@ -19,7 +19,6 @@ export class LoginComponent {
 
   form: FormGroup;
   error: string|null = null;
-  token: string|null = null;
   isLoading : boolean = false;
 
   constructor(private fb: FormBuilder) {
@@ -30,7 +29,6 @@ export class LoginComponent {
   }
 
   ngOnInit() {
-    this.store.select(selectToken).subscribe(token => (this.token = token));
     this.store.select(selectError).subscribe(error => (this.error = error));
     this.store.select(selectIsLoading).subscribe(isLoading => (this.isLoading = isLoading));
   }
index 9c39495755de1bd954b8328108af0afff8e3e1c1..959b7c412d0d429ff9c4b321e1423aaaa20bbf26 100644 (file)
@@ -2,15 +2,26 @@ import { inject, Injectable } from '@angular/core';
 import { Router } from "@angular/router";
 import { Observable, of, throwError } from 'rxjs';
 import { delay } from 'rxjs/operators';
+import { Store } from '@ngrx/store';
+import { selectError, selectToken } from '../store/login.selectors';
 
 @Injectable({
   providedIn: 'root'
 })
 export class AuthService {
   private router = inject(Router);
+  private store = inject(Store);
 
   private username : string|undefined;
 
+  ngOnInit() {
+    this.store.select(selectToken).subscribe(username => {
+      this.username = username;
+      this.router.navigate(['']);
+    });
+    this.store.select(selectError).subscribe(error => (this.username = undefined));
+  }
+
   login(username : string, password : string) : Observable<string> {
     const shouldFail = Math.random() < 0.3; // 30% Fehlerchance
     if (shouldFail) {