Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReturnUrl in angular

Tags:

angular

The project I'm currently working on, I wanted to apply returnUrl to the login. I have attached the code here. When I try to initialize returnUrl inside the ngOnInit(), it doesn't work properly. But if I initialize returnUrl inside the login method, it works. What can be the problem here?

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { LoginUser } from '../_models/LoginUser';
import { AlertifyService } from '../_services/alertify.service';
import { AuthService } from '../_services/auth.service';

@Component({
  selector: 'app-nav',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})

export class NavBarComponent implements OnInit {
  user: LoginUser = { username: '', password: '' };
  photoUrl: string;

  constructor(
    public authService: AuthService,
    private alertify: AlertifyService,
    private router: Router,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.authService.currentPhotoUrl.subscribe(photoUrl => this.photoUrl = photoUrl);
  }

  login() {
    let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/members';
    this.authService.login(this.user).subscribe(data => {
      this.router.navigateByUrl(returnUrl);
    }, error => {
      this.alertify.error('Login Failed');
    }, () => {
      this.alertify.success('Login Successful');
    });
  }

  logout() {
    this.authService.userToken = null;
    this.authService.currentUser = null;

    localStorage.removeItem('token');
    localStorage.removeItem('user');

    this.alertify.message('logged out');
    this.router.navigate(['/home']);
  }

  loggedIn() {
    return this.authService.loggedIn();
  }

}
like image 218
Shashika Avatar asked Oct 15 '25 04:10

Shashika


1 Answers

Why don't use AuthGuard and override the canActivate

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    .....
    .....        
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
}
like image 138
jprism Avatar answered Oct 17 '25 19:10

jprism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!