4

When the angular app loads, it should show the login component and then be navigated to the App Component on successful login.

The code follows,

app.module.ts

bootstrap: [LoginComponent]

app-routing.module.ts

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: AddUserComponent, canActivate: [AuthGuard] }
}

AuthGuard

export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) { }

  canActivate(route, state: RouterStateSnapshot)
  {
    this.authService.isLoggedIn.subscribe(data => {

      if (data) 
        this.router.navigate(['/home'])


        this.router.navigate(['/login'], { queryParams:{ returnUrl: state.url }})


      return false;
    });

    return true;
  }
}

AuthService

export class AuthService {

  constructor(private httpClient: HttpClient) { }

  private _loggedIn = new BehaviorSubject<boolean>(false);

  isLoggedIn = this._loggedIn.asObservable()

  login() : Observable<boolean>
  {
     this._loggedIn.next(true);

     return this.isLoggedIn
  }
}

But after login, it is not navigating to the Home Component and it always stays in the Login Component and the login page loads again?

Stackblitz

6
  • Should that be an else in your AuthGuard? Commented Jul 13, 2019 at 17:35
  • No that doesn't work and I think something else I am missing Commented Jul 13, 2019 at 17:44
  • Can you provide a working stackblitz of the same? Commented Jul 13, 2019 at 17:52
  • stackblitz.com/edit/angular-7-master-h1c2t5 Commented Jul 13, 2019 at 19:16
  • I get this error on opening your stackblitz ERROR Error: The selector "app-root" did not match any elements Commented Jul 14, 2019 at 9:45

1 Answer 1

2

Stackblitz link:- https://stackblitz.com/edit/angular-7-master-pcbnsy?file=src%2Fapp%2Fapp.component.ts

app.module.ts <=== if registered parent module

@NgModule({
  imports:      [ BrowserModule, FormsModule,AppRoutingModule, HttpClientModule, ],
  declarations: [ AppComponent, HelloComponent, LoginComponent ],
   providers: [
     AuthGuard,
    AuthService
  ],
  bootstrap:    [ AppComponent ],

})
export class AppModule { }

routing.ts

const routes: Routes = [
     {path: '', redirectTo: 'home', pathMatch: "full"},
  { path: 'login', component: LoginComponent},

  { path: 'home', component: HelloComponent, canActivate: [AuthGuard] },

];

login.component.ts

  login():any{

    console.log("login")

    this.authService.login(true)
   this.router.navigate(['/home']);
  }

guard.ts

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


@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) { }

  canActivate(route, state: RouterStateSnapshot)
  {
    this.authService.isLoggedIn.subscribe(data => {

      console.log('sssss::' + data);

      if (data) 
      {
     return true;
      }
     else{
        this.router.navigate(['/login'], { queryParams:{ returnUrl: state.url }})
       return false;
}
    });


    return true;
  }
}

auth.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of as observableOf, BehaviorSubject  } from 'rxjs';

@Injectable()
export class AuthService {

  constructor(private httpClient: HttpClient) { }

  // private _loggedIn = new BehaviorSubject<boolean>(false);
  // isLoggedIn = this._loggedIn.asObservable()
 public isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);

  login(value: boolean) 
  {
  this.isLoggedIn.next(value);

  }

  register() {

  }

  logout (){
    this.isLoggedIn.next(false);
  }


}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.