【问题标题】:ReturnUrl in angularReturnUrl 角度
【发布时间】:2018-03-05 07:35:27
【问题描述】:

我目前正在进行的项目,我想将 returnUrl 应用于登录。我在这里附上了代码。当我尝试在 ngOnInit() 中初始化 returnUrl 时,它无法正常工作。但是,如果我在登录方法中初始化 returnUrl,它就可以工作。这可能是什么问题?

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();
  }

}

【问题讨论】:

  • 放在OnInit里面有什么问题?
  • 如果我把它放在 ngOnInit 中,returnUrl 是未定义的。让 returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/成员';此行在 Login 方法中正常工作。但是以下行不起作用。它说 returnUrl 是未定义的。 returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/成员';
  • 如果你把它放在 ngOnInit 方法中你应该像 photoUrl 一样声明上面的变量并在登录方法中调用 this.returnUrl
  • 我就是这么用的。但它说它是未定义的。
  • 这个答案可能有用:stackoverflow.com/a/59008239/7059557

标签: angular


【解决方案1】:

为什么不使用 AuthGuard 并覆盖 canActivate

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    .....
    .....        
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
}

【讨论】:

  • 这是一种更简洁的方法!
  • 或者更好,return this.router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url }});
猜你喜欢
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
  • 2011-02-10
  • 2018-04-05
  • 1970-01-01
  • 2013-07-07
  • 2011-07-25
相关资源
最近更新 更多