From: Kai Moritz Date: Sun, 7 Sep 2025 00:26:33 +0000 (+0200) Subject: auth service asserts redirect to `login`, if the user is not yet set X-Git-Url: https://juplo.de/gitweb/?a=commitdiff_plain;h=707a029329b8f961a5bcaf2f04e1fde73d96e607;p=demos%2Fangular%2Fstored-login auth service asserts redirect to `login`, if the user is not yet set --- diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 61a67e8..a7422aa 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -1,5 +1,6 @@ -import { Component } from '@angular/core'; +import { Component, inject } from '@angular/core'; import { RouterOutlet } from '@angular/router'; +import { AuthService } from './services/auth.service'; @Component({ selector: 'app-root', @@ -8,5 +9,12 @@ import { RouterOutlet } from '@angular/router'; styleUrl: './app.component.less' }) 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 0ca20a4..dfd2858 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -1,13 +1,22 @@ -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { Router } from "@angular/router"; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { + private router = inject(Router); + private username : string|undefined; login(username : string, password : string) : Observable { return of(username); } + + assertUserIsKnown(): void { + if(!this.username) { + this.router.navigate(['login']); + } + } }