简体   繁体   中英

Redirect to login page after logout in angular app

In my angular app, I redirect the user from home to the login page after logout. It works for a few seconds then angular redirects to the home page again.

// routing paths

RouterModule.forRoot([
        {path:"", component: HomeComponent , canActivate: [AuthGuard]},
        {path:"login", component: LoginComponent},
        {path:"signup", component: SignupComponent},
])

// AuthService.service.ts

import { AngularFireAuth } from '@angular/fire/compat/auth';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  loggedUser!: any;

  constructor(
    private router: Router,
    private auth: AngularFireAuth,
    private fireStore: AngularFirestore
  ) {}

 get isLoggedIn() {
    return this.loggedUser !== null;
  }
   
 // logout function 
    async signout() {
       await this.auth.signOut();
       localStorage.removeItem('user');
       this.loggedUser = null; 
       this.router.navigate(['login']);
    }
}

export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router : Router){

    }
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        if(!this.authService.isLoggedIn){
            this.router.navigate(['login']);
        }
        return true;
  }
  
}

You have to add pathMatch: 'full' to you empty path

 {path:"", component: HomeComponent , pathMatch: 'full', canActivate: [AuthGuard]},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM