Значение isAuthenticated не обновляется и маршрут не выполняется - PullRequest
0 голосов
/ 03 мая 2020

my authGuard работает правильно, когда пользователь не прошел проверку подлинности и не перешел на страницу входа, но когда я нажал кнопку входа , пользователь сохраняется в моем localStorage и все данные обновляются , но маршрутизация не происходит для любого компонента, который имеет authGuard

authService

import { Injectable, Output, EventEmitter } from '@angular/core';
import { UsersService } from './users.service';

import { AngularFirestore } from '@angular/fire/firestore';
import { Router } from '@angular/router';
import { BehaviorSubject, Subject, Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators/map';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private currentUserSubject = new BehaviorSubject<any>(this.decodeUser());
  public currentUser = this.currentUserSubject.asObservable();

  private isAuthanticatedSubject = new BehaviorSubject<any>(this.hasLoggedInUser());
  public isAuthanticated = this.isAuthanticatedSubject.asObservable();
  constructor(
    private router: Router,
    private db: AngularFirestore
  ) {}

  logoutBtn
  login(username,password){
    return this.db.collection('users', ref=> ref.where(`username`, '==', username).where('password', '==', password))
    .snapshotChanges().pipe(map(res => {
      const user = res.map((u:any) => ({
        id: u.payload.doc.id,
        fullname: u.payload.doc.data().fullname,
        role: u.payload.doc.data().role
        //...u.payload.doc.data()
      }))
      if(!user[0])  return false;


      console.log(user[0])
      localStorage.setItem('currentUser' , JSON.stringify(user[0]))
      this.currentUserSubject.next(user[0])
      this.router.navigate(['/admin/admin'])
      return true;
    }))
  }
  private decodeUser(){
    const user = localStorage.getItem('currentUser')
    return user? JSON.parse(user) :  {}
  }
  private hasLoggedInUser(){
    return !!localStorage.getItem('currentUser')
  }
  logout(){
    localStorage.removeItem('currentUser')
    this.isAuthanticatedSubject.next(false)
    this.currentUserSubject.next({})
    this.router.navigate(['/home'])
  }
}

authGuard.service

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthService,
    private router: Router
  ) { }
  canActivate(){
    this.auth.isAuthanticated.subscribe(res => console.log(res))

    return this.auth.isAuthanticated.pipe(map(isAuth => {
      if(!isAuth){
        this.router.navigate(['/admin/login']);
        return false
      }
      if(isAuth){
        return true;
      }
      console.log(isAuth)
    }))

  }

}

admin-routing.module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AdminComponent } from './admin.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from '../home/components/home/home.component';
import { UsersComponent } from './components/users/users.component';
import { AuthGuard } from '../services/auth-guard.service';


const routes: Routes = [

  {
    path:'',
    component: LoginComponent
  },
  {
    path:'login',
    component: LoginComponent
  },
  {
    path:'admin',
    component: AdminComponent,
    canActivate: [AuthGuard]
  },
  {
    path:'users',
    component: UsersComponent,
    canActivate: [AuthGuard]
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }

admin.module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { AdminRoutingModule } from './admin-routing.module';
import { AdminComponent } from './admin.component';
import { SharedModule } from '../shared/shared.module';
import { LoginComponent } from './components/login/login.component';
import { BookingListComponent } from './components/booking-list/booking-list.component';
import { BookingGridComponent } from './components/booking-grid/booking-grid.component';
import { MalakComponent } from '../home/components/malak/malak.component';
import { HomeModule } from '../home/home.module';
import { RepeatDayComponent } from './components/repeat-day/repeat-day.component';
import { UsersComponent } from './components/users/users.component';
import { RoleService } from '../services/role.service';
import { AuthGuard } from '../services/auth-guard.service';


@NgModule({
  declarations: [AdminComponent, LoginComponent, BookingListComponent, BookingGridComponent, RepeatDayComponent, UsersComponent,],
  imports: [
    CommonModule,
    AdminRoutingModule,
    SharedModule,
    HomeModule
  ],
  providers: [RoleService, AuthGuard],
  exports: [RepeatDayComponent],
  entryComponents: [RepeatDayComponent]

})
export class AdminModule { }

login.component

import { Component, OnInit, Input, EventEmitter, Output, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { UsersService } from 'src/app/services/users.service';
import { AuthService } from 'src/app/services/auth.service';
import { async } from '@angular/core/testing';
import { take, map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { RoleService } from 'src/app/services/role.service';
import { AdminComponent } from '../../admin.component';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  constructor(
    private router: Router,
    private rs: RoleService,
    private auth: AuthService
  ) { }

  admin = true
  loginError: boolean = false
  user
  ngOnInit() {


  }
  userLog;
  submit(f) {
    this.auth.login(f.username, f.password).subscribe(res => {
      console.log(res)
      if (res) {
        this.router.navigate(['/admin/admin'])
      }
    })
  }
}
...