Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

making a chat app with angular, after activating Authguard, when trying to login, it keeps redirecting me to my login page instead of chat page

I have been having problems navigating into my chat session since i added AuthGuard to the app.routes, It keeps navigating me to the login page

Below is my AuthService.ts

import { Injectable } from '@angular/core';
import { Router ,Routes } from '@angular/router';
import { User } from '../classes/user';
import { Alert } from './../classes/alert';
import { AlertService } from './alert.service';
import { fromPromise } from 'rxjs/observable/fromPromise';

import { AlertType } from './../enums/alert-type.enum';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/fromPromise';
import { of } from 'rxjs/Observable/of';
import {Observable} from 'rxjs/Observable';


@Injectable()
export class AuthService {
  public currentUser: Observable<User|null>;
  constructor( private router: Router,
    private alertService: AlertService,
    private afAuth: AngularFireAuth,
    private db: AngularFirestore,
      ) {
    // TODO fetch the user from the Firebase backend, then set the user
    this.currentUser = this.afAuth.authState
    .switchMap((user) => {
      if (user) {
        return this.db.doc<User>(`users/${user.uid}`).valueChanges();
      } else {
        return of(null);
      }
    })
  }
   public signup(firstName: string, lastName: string, userName: string, DOB:string, eMail:string,phoneNumber: string,passWord:string): Observable<boolean> {
    return fromPromise(
      this.afAuth.auth.createUserWithEmailAndPassword(eMail,passWord)
      .then((user) => {
        const userRef: AngularFirestoreDocument<User> = this.db.doc(`users/${user.user.uid}`);
        const updatedUser = {
          id: user.user.uid,
          eMail:eMail,
          firstName,
          lastName,
          photoUrl:'https://firebasestorage.googleapis.com/v0/b/university-konnect.appspot.com/o/Snapchat-11969475.jpg?alt=media&token=f37e5f50-d73f-46ec-badf-eb206d7dfb9c'
        }

        userRef.set(updatedUser)
        return true;
      })
      .catch((err) => false)
  );
  }

  public login(email: string, password: string): Observable<boolean> {
    // TODO call Firebase login function
    return fromPromise(
      this.afAuth.auth.signInWithEmailAndPassword(email,password)
      .then((user)=>true)
      .catch((err)=>false)
    );
  }


}

below is my AuthGuard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { map, take, tap } from 'rxjs/operators';
import { AlertService } from './../services/alert.service';
import { Alert } from './../classes/alert';
import { AlertType } from './../enums/alert-type.enum';
import { AuthService } from './../services/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthService,
    private router: Router,
    private alertService: AlertService
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
    return this.auth.currentUser.pipe(
      take(1),
      map((currentUser) => !!currentUser),
      tap((loggedIn) => {
        if (!loggedIn) {
          this.alertService.alerts.next(new Alert('You must be logged in to access that page.', AlertType.Danger));
          this.router.navigate(['/login'], {queryParams: { returnUrl: state.url }});
        }
      })
    )
}
}

Below is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { NgModule } from '@angular/core';
import { AlertModule } from "ngx-bootstrap";
import { FormsModule} from '@angular/forms';
import { HttpClientModule } from "@angular/common/http";
import { ReactiveFormsModule} from '@angular/forms';
import { NgxLoadingModule, NgxLoadingService } from 'ngx-loading';
import { AlertService } from './services/alert.service';
import { Alert } from './enums/alert';
import { AppRoutingModule } from './app-routing';
import { RouterModule , Router ,Routes, ROUTES} from '@angular/router'
import { AppComponent } from './app.component';
import { RegisterComponent } from './register/register.component';
import {LoadingService} from './services/loading.service';
import { DataService } from "./data.service";
import { CompleteprofileComponent } from './register/completeprofile/completeprofile.component';
import { LoginComponent } from './login/login.component';
import { HandoutsComponent } from './handouts/handouts.component';
import { ChatComponent } from './pages/chat/chat.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { ChatInputComponent } from './pages/chat/components/chat-input/chat-input.component';
import { ChatMessagesComponent } from './pages/chat/components/chat-messages/chat-messages.component';
import { ChatroomListComponent } from './pages/chat/components/chatroom-list/chatroom-list.component';
import { ChatroomTitleBarComponent } from './pages/chat/components/chatroom-title-bar/chatroom-title-bar.component';
import { ChatroomWindowComponent } from './pages/chat/components/chatroom-window/chatroom-window.component';
import { AuthService } from "./services/auth.service";
import { AuthGuard } from "./guards/auth.guard";
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { AngularFireStorageModule } from 'angularfire2/storage';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { environment } from '../environments/environment';





@NgModule({
  declarations: [
    AppComponent,
    RegisterComponent,
    CompleteprofileComponent,
    LoginComponent,
    HandoutsComponent,
    ChatComponent,
    NavbarComponent,
    ChatInputComponent,
    ChatMessagesComponent,
    ChatroomListComponent,
    ChatroomTitleBarComponent,
    ChatroomWindowComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    AlertModule.forRoot(),
    FormsModule,
    ReactiveFormsModule,
    NgxLoadingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    AngularFireStorageModule,
    AngularFireAuthModule,


  ],
  providers: [DataService , AlertService,NgxLoadingService,LoadingService,AuthService,AuthGuard],
  bootstrap: [AppComponent],
  schemas: [
    NO_ERRORS_SCHEMA
  ],
})
export class AppModule { }

Below is my register.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Routes,RouterModule } from "@angular/router";
import { FormBuilder,FormGroup,Validators } from "@angular/forms";
import { AlertService } from '../services/alert.service';
import { Alert} from '../enums/alert';
import { AlertType} from '../enums/alert-type.enum';
import {LoadingService} from 'src/app/services/loading.service';
import { NgxLoadingService } from 'ngx-loading';
import { Subscription } from "rxjs/Subscription";
import { AuthService } from "./../services/auth.service";
import { Router, ActivatedRoute } from '@angular/router';
import { Subscriber } from 'rxjs/Subscriber';
import { of } from 'rxjs/Observable/of';



@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css', './../app.component.css']
})
export class RegisterComponent implements OnInit, OnDestroy {
  public signupForm:FormGroup;
  private subscriptions: Subscription[] = [];

  constructor(private fb: FormBuilder,
     private alertService : AlertService,
     private auth: AuthService,
    private loadingService: LoadingService,
    private router: Router ,
    ) {
    this.createForm();
  }


  ngOnInit() {
  }
  private createForm():void {
    this.signupForm=this.fb.group({
      firstName:['',[Validators.required,Validators]],
      lastName:['',[Validators.required]],
      userName:['',[Validators.required]],
      DOB:['',[Validators.required]],
      eMail:['',[Validators.required,Validators.email]],
      phoneNumber:['',[Validators.required,Validators.minLength(8),Validators.maxLength(11)]],
       passWord:['',[Validators.required,Validators.minLength(6)]]
    });

  }
  public submit():void {
    if (this.signupForm.valid){
    const {firstName,lastName,userName,DOB,eMail,phoneNumber,passWord,} = this.signupForm.value;
//TODO CALL AUTH SERVICE
     this.subscriptions.push(
       this.auth.signup(firstName,lastName,userName,DOB,eMail,phoneNumber,passWord).subscribe(success => {
         if (success) {
          this.router.navigate(['/chat']);
         }else{
           const failedSignupAlert = new Alert('There was a problem signing up ,Try again ',AlertType.Danger)
           this.alertService.alerts.next(failedSignupAlert);
         }

         this.loadingService.isLoading.next(false);
       })
     )}else{
    const failedSignupAlert = new Alert( 'please enter a valid name,Email and password,Try again',AlertType.Danger)
    this.alertService.alerts.next(failedSignupAlert);
     }
 }

ngOnDestroy() {
  this.subscriptions.forEach(sub => sub.unsubscribe());
}

}

Below is my App.routing.ts

import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RegisterComponent } from "./register/register.component";
import {  CompleteprofileComponent } from "./register/completeprofile/completeprofile.component";
import { LoginComponent } from './login/login.component';
import { HandoutsComponent } from './handouts/handouts.component';
import { AuthService } from 'src/app/services/auth.service';
import { ChatComponent } from './pages/chat/chat.component';
import { AuthGuard } from './guards/auth.guard';
const routes: Routes = [
  {
    path: 'register',
    component: RegisterComponent,
    data: {title: "Register Component"} ,

    },
    {
      path: 'completeprofile',
      component: CompleteprofileComponent,
      data: {title: " Completeprofile Component"} ,
      },
      {
        path: 'chat',
        component: ChatComponent, canActivate:[AuthGuard],

        },

     {path: 'login',
      component: LoginComponent,
      data : {title: "login Component"}
     },

     {path: '', pathMatch: 'full', redirectTo: '/login'},

     {path: '**', pathMatch: 'full', redirectTo: '/login'},

      {path: 'handouts',
      component: HandoutsComponent,
      data : {title: "Handouts Component"} },

];

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

I would be really Thankful if i get a quick response

Comments